c# - 在 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;
已尝试订阅自身的MouseClick
和KeyPress
事件Form
,但该事件似乎没有触发。如上所述,只有在使用特定控制事件时,它才会起作用。
解决方案
窗体的 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);
}
推荐阅读
- swift - 传输数据时,返回 nil。在隐式展开可选值时意外发现 nil
- shell - 是否可以为一个进程锁定/保留 GPU?
- reactjs - 如何从初始值正确组织属性对象数组
- javascript - Dajango中必填字段的表单验证错误
- python - 如何在 python 上下载在线库?
- chef-infra - 运行 Chef Client 时 systemd 单元验证失败
- android - Android webview全屏显示视频不起作用
- c++ - TensorRT (C++ API) 未定义对“createNvOnnxParser_INTERNAL”的引用
- python - 如何在熊猫数据框中使用连接方法
- dictionary - 是否可以在包含地图名称的同时编组一个 go 结构?