Distinguish Between Touch/Pen and Mouse Input in WinForms

In WinForms, mouse events are raised regardless of the original source of the mouse. If you click a button with the stylus for instance, you’d still get the MouseClick event. This MSDN page explains how to distinguish between the sources of the event. To make the long story short, you’d have to place an API call to the GetMessageExtraInfo() function and check the returned value. The following C# code snippet performs the checking:

/// <summary>
/// The sources of the input event that is raised and is generally
/// recognized as mouse events.
/// </summary>
public enum MouseEventSource
{
    /// <summary>
    /// Events raised by the mouse
    /// </summary>
    Mouse,

    /// <summary>
    /// Events raised by a stylus
    /// </summary>
    Pen,

    /// <summary>
    /// Events raised by touching the screen
    /// </summary>
    Touch
}

/// <summary>
/// Gets the extra information for the mouse event.
/// </summary>
/// <returns>The extra information provided by Windows API</returns>
[DllImport("user32.dll")]
private static extern uint GetMessageExtraInfo();

/// <summary>
/// Determines what input device triggered the mouse event.
/// </summary>
/// <returns>
/// A result indicating whether the last mouse event was triggered
/// by a touch, pen or the mouse.
/// </returns>
public static MouseEventSource GetMouseEventSource()
{
    uint extra = GetMessageExtraInfo();
    bool isTouchOrPen = ((extra & 0xFFFFFF00) == 0xFF515700);

    if (!isTouchOrPen)
        return MouseEventSource.Mouse;

    bool isTouch = ((extra & 0x00000080) == 0x00000080);

    return isTouch ? MouseEventSource.Touch : MouseEventSource.Pen;
}

 

Leave a Reply

Your email address will not be published.