WinForm

Winform WndProc与多线程交互

小樊
82
2024-08-23 18:26:31
栏目: 智能运维

在Winform中,WndProc是窗口过程,负责处理窗口消息。在多线程中,如果需要在其他线程中更新UI控件,需要通过Invoke方法来在UI线程中执行相应的代码。下面是一个示例代码,演示了如何在多线程中更新UI控件:

using System;
using System.Threading;
using System.Windows.Forms;

namespace MultiThreadWinform
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void UpdateLabel(string text)
        {
            if (label1.InvokeRequired)
            {
                label1.Invoke(new Action<string>(UpdateLabel), text);
            }
            else
            {
                label1.Text = text;
            }
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_USER = 0x0400;
            const int WM_UPDATE_LABEL = WM_USER + 1;

            switch (m.Msg)
            {
                case WM_UPDATE_LABEL:
                    UpdateLabel("Update by WndProc");
                    break;
            }

            base.WndProc(ref m);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                Thread.Sleep(2000);
                this.BeginInvoke(new Action(() =>
                {
                    UpdateLabel("Update by thread");
                }));

                this.Invoke(new Action(() =>
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        this.WndProc(ref Message.Create(this.Handle, WM_UPDATE_LABEL, IntPtr.Zero, IntPtr.Zero));
                    }));
                }));
            });
            thread.Start();
        }
    }
}

在上面的示例代码中,通过Override WndProc方法,定义了一个自定义的窗口消息WM_UPDATE_LABEL,当收到这个消息时,会调用UpdateLabel方法更新UI控件。在button1_Click事件中,启动一个新线程,在新线程中通过Invoke和BeginInvoke方法更新UI控件,并向WndProc发送自定义消息来更新UI控件。这样就实现了在多线程中更新UI控件的功能。

0
看了该问题的人还看了