首页 > 解决方案 > 在 WinForms 中检测表单(包括控件)上的任意位置单击

问题描述

一个 WinForms 应用程序,其中某个 UI 控件必须在用户与窗口交互后 5 秒消失(单击窗体上的任何位置,包括任何控件或按键)。

假设发生这种情况时会触发事件,以下是事件处理程序:

private async void userInteract(object sender, System.EventArgs e)
{
    if (progressBarFinished)
    {
        await Task.Delay(5000);
        statusIdle(); // this method hides a progress bar after 5 seconds. It is working.
    }
}

在表单构造函数中,订阅事件如下:

// at the moment, it is not working for when a user clicks anywhere on the form
// it is working when a specific control click event occurs, like this one
progressBar.Click += userInteract;

已尝试订阅自身的MouseClickKeyPress事件Form,但该事件似乎没有触发。如上所述,只有在使用特定控制事件时,它才会起作用。

标签: c#.netformswinformsevents

解决方案


窗体的 WndProc 方法处理由 Windows 操作系统发送到窗体的消息。这是一种极其重要的方法,它允许表单移动、调整大小、重新绘制和执行其他关键操作。

    // Constants for decoding the Win32 message.
    protected const int WM_MOUSEACTIVATE = 0x0021;
    protected const int WM_LBUTTONDOWN = 0x201;
    protected const int WM_RBUTTONDOWN = 0x204;

    protected override void WndProc(ref Message m)
    {
        // Check the Message parameter to see if the message is WM_MOUSEACTIVATE indicating that a control was clicked.
        if (m.Msg == WM_MOUSEACTIVATE)
        {
            int wparam = m.WParam.ToInt32();

            if (wparam == WM_LBUTTONDOWN || wparam == WM_RBUTTONDOWN)
            {
                // TODO: Do something with the mouse event.
                Console.WriteLine(m);

                return;
            }
        }

        base.WndProc(ref m);
    }

参考 1

参考 2


推荐阅读