开发者

How to tell what physical device clicked a button in C#?

开发者 https://www.devze.com 2023-01-13 01:25 出处:网络
I have a Form with buttons. This application is meant to run开发者_如何学运维 on a touchscreen computer. When a button is clicked I would like to know whether it was clicked by the mouse or the touchs

I have a Form with buttons. This application is meant to run开发者_如何学运维 on a touchscreen computer. When a button is clicked I would like to know whether it was clicked by the mouse or the touchscreen.

Is this possible? If so, how?


private void button_Click(object sender, EventArgs e)
{
    try
    {
        ((MouseEventArgs)e).Button.ToString();
    }
    catch(Exception)
    {
        //If an exception is catch, it means the mouse was not used.
    }
}

This is a gross way to do it, because it will catch an exception anytime button is "clicked" by something else than the mouse, either touchscreen or keyboard's return. But it will do the job :)


Taking from Wildhorn's answer this way avoids the exceptions being thrown:

MouseEventArgs thisObject = e as MouseEventArgs

if(thisObject != null)
{
//Do Something
}

It's not much different but you don't have the overhead of the exception handling. Also you could try multiple casts til you got the right one.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号