Home > Software engineering >  Global mouse down detection
Global mouse down detection

Time:12-16

How can I detect when a mouse is down (globablly) on Windows through C#? I'm trying to bind a function to when my, e.g., right button is down.

How it would work:
Right mouse button down -> On event call -> Function called
Right mouse button up -> On event call -> Function called

CodePudding user response:

Maybe you can use this , MouseClick or MouseWheel . I test it and convert it from vb.net to C#

 private void Form1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
{
    if (e.Delta > 0)
        MessageBox.Show("Up");
    else
        MessageBox.Show("Down");
}

private void Form1_MouseClick(object sender, MouseEventArgs e)
{
    switch (e.Button)
    {
        case object _ when MouseButtons.Left:
            {
                MessageBox.Show(this, "Left Button Click");
                break;
            }

        case object _ when MouseButtons.Right:
            {
                MessageBox.Show(this, "Right Button Click");
                break;
            }

        case object _ when MouseButtons.Middle:
            {
                break;
            }

        default:
            {
                break;
            }
    }

CodePudding user response:

If you are working with XAML and need to detect a mouse up/down event in C#,

<Grid Name="pnlMainGrid" MouseUp="pnlMainGrid_MouseUp" Margin="10">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>


    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>

    <Label>Names</Label>
</Grid>

Then you need to define the Mouse up event

        private void pnlMainGrid_MouseUp(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("You clicked me");
    }

The logic goes, click on the label (you can define this to be other things such as a button, a layout, etc) Call the pnlMainGrid_MouseUp function, the function shows a message.

CodePudding user response:

You can use Windows Hooks from WinApi. An example named "Download source files [Version 2]" from codeproject article https://www.codeproject.com/Articles/7294/Processing-Global-Mouse-and-Keyboard-Hooks-in-C contains static class named HookManager.

When you subscribe to HookManager.MouseClick, you will receive a callback on every mouse click on any window in your system (not just in your app). And Button property of MouseEventArgs e parameter will help you to determine which button is clicked.

See TestFormStatic class in example project.

  • Related