另一种方法是使用PeekMessage API函数,如下代码所示。
using System.Runtime.InteropServices;
using System.Security;
[StructLayout(LayoutKind.Sequential)]
public struct NativeMessage
{
public IntPtr handle;
public uint msg;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
public System.Drawing.Point p;
}
[SuppressUnmanagedCodeSecurity]
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("User32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool PeekMessage(out NativeMessage message,
IntPtr handle, uint filterMin, uint filterMax, uint flags);
private const UInt32 WM_MOUSEFIRST = 0x0200;
private const UInt32 WM_MOUSELAST = 0x020D;
public const int PM_REMOVE = 0x0001;
// Flush all pending mouse events.
private void FlushMouseMessages()
{
NativeMessage msg;
// Repeat until PeekMessage returns false.
while (PeekMessage(out msg, IntPtr.Zero,
WM_MOUSEFIRST, WM_MOUSELAST, PM_REMOVE))
;
}
此代码包含一堆 API 函数及其参数的声明。 (您还需要为 System.Runtime.InteropServices 和 System.Security 命名空间添加 using 语句。下载示例了解详细信息。)
FlushMouseMessages 方法调用 PeekMessage 告诉它丢弃 WM_MOUSELAST 到 PM_REMOVE 范围内的任何消息。代码重复调用 PeekMessage 直到返回 false 表示没有此类消息。
以下按钮事件处理程序调用 FlushMouseMessage,因此您无法在其代码仍在运行时单击该按钮。
private void but_Click(object sender, RoutedEventArgs e)
{
(sender as Button).IsEnabled = false;
doSomeThing();//e.g run for more than 20 seconds
(sender as Button).IsEnabled = true;
FlushMouseMessages();
}
我从网站上选择了上面的代码
http://csharphelper.com/blog/2015/08/flush-click-events-in-c/
这对我有用。