gpt4 book ai didi

c# - 如何更新 WPF MainWindow 上的控件

转载 作者:太空狗 更新时间:2023-10-30 00:25:13 26 4
gpt4 key购买 nike

如何在下面的代码中更新我的 label1 文本?我收到“调用线程无法访问此对象,因为另一个线程拥有它”错误。我读到过其他人使用过 Dispatcher.BeginInvoke,但我不知道如何在我的代码中实现它。

public partial class MainWindow : Window
{
System.Timers.Timer timer;

[DllImport("user32.dll")]
public static extern Boolean GetLastInputInfo(ref tagLASTINPUTINFO plii);

public struct tagLASTINPUTINFO
{
public uint cbSize;
public Int32 dwTime;
}

public MainWindow()
{
InitializeComponent();
StartTimer();
//webb1.Navigate("http://yahoo.com");
}

private void StartTimer()
{
timer = new System.Timers.Timer();
timer.Interval = 100;
timer.Elapsed += timer_Elapsed;
timer.Start();
}

void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
tagLASTINPUTINFO LastInput = new tagLASTINPUTINFO();
Int32 IdleTime;
LastInput.cbSize = (uint)Marshal.SizeOf(LastInput);
LastInput.dwTime = 0;

if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
string s = IdleTime.ToString();
label1.Content = s;
}
}
}

最佳答案

你可以尝试这样的事情:

if (GetLastInputInfo(ref LastInput))
{
IdleTime = System.Environment.TickCount - LastInput.dwTime;
string s = IdleTime.ToString();

Dispatcher.BeginInvoke(new Action(() =>
{
label1.Content = s;
}));
}

阅读更多关于 Dispatcher.BeginInvoke Method here 的信息

关于c# - 如何更新 WPF MainWindow 上的控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com