April 13, 2007

Discarding Pending Mouse Or Keyboard Messages in C#

public static class Win32Helper

/// Window messages
private enum WindowMessage : uint
    // Keyboard messages
    KeyboardFirst = 0x0100,
    KeyboardLast = 0x0108,

    // Mouse messages
    //MouseMove = 0x0200,
    MouseFirst = 0x0201, // Skip mouse move, it happens 
                         //a lot and there is another message for that
    MouseLast = 0x020d,

public static void DiscardMousebMessages(IntPtr hWnd)
    Message msg;
    while (PeekMessage(out msg, hWnd, (uint)WindowMessage.MouseFirst,
        (uint)WindowMessage.MouseLast, (uint)PeekMessageFlags.PM_REMOVE)) ;

public static void DiscardKeyboardMessages(IntPtr hWnd)
    Message msg;
    while (PeekMessage(out msg, hWnd, (uint)WindowMessage.KeyboardFirst,
        (uint)WindowMessage.KeyboardLast, (uint)PeekMessageFlags.PM_REMOVE)) ;

private struct Message
    public IntPtr hWnd;
    public WindowMessage msg;
    public IntPtr wParam;
    public IntPtr lParam;
    public uint time;
    public System.Drawing.Point p;

[DllImport("User32.dll", CharSet = CharSet.Auto)]
private static extern bool PeekMessage(
    out Message msg, IntPtr hWnd, 
    uint messageFilterMin, uint messageFilterMax, 
    uint flags);


No comments: