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

标签 c# wpf multithreading

如何在下面的代码中更新我的 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/

相关文章:

c# - Serverless API Gateway/Lambda 下载 PDF 失败

c# - Windows 10 专业版 1803 蓝牙配置文件访问

c# - 如何让 XAML 中的图像显示为它们的实际大小?

c# - 如何从 C# 代码访问 wpf 中的 ResourceDictionary?

c# - 如何使用任务并行库从SQL表中批量读取大量记录

python - 如何在 Sqlalchemy orm session 中正确禁用缓存?

ios - 核心数据多线程应用

c# - 更正 EF 6 中 AddOrUpdate() 的多个条件

c# - C# 方法是否允许可空列表作为参数?

c# - 使用 linq 将 xml 文件加载到二维矩形数组中