I have a Windows Forms Application in C# which monitors if the mouse buttons are being held down. There is a primary thread for the GUI, which spawns a secondary STA thread. This code never executes within it:
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
System.Diagnostics.Debug.WriteLine("Left mouse down");
}
I wondered if this is because I have the following STA option enabled for the thread?
repeaterThread.SetApartmentState(ApartmentState.STA);
repeaterThread.Start();
Full relevant code:
I'm using PresentationCore.dll
, and System.Windows.Input
;
Winforms GUI:
On start button pressed:
...
Thread repeaterThread = new Thread(() => ListenerThread());
repeaterThread.SetApartmentState(ApartmentState.STA);
repeaterThread.Start();
...
ListenerThread method:
public static void ListenerThread()
{
while(true)
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
System.Diagnostics.Debug.WriteLine("Left mouse down");
}
Thread.sleep(1000);
}
}
How can I capture if the mouse button is being held down from this thread?
Thanks
The following example shows how to determine whether the left mouse button is pressed by checking if the state of the LeftButton is equal to the MouseButtonState enumeration value Pressed. If the button is pressed, a method is called which updates display elements in the sample.
The following example shows a mouse event handler that determines which buttons are currently pressed by checking the button state of each mouse button. The MouseButtonState enumeration specifies constants which correlate to the state of a mouse button.
Specifies the possible states of a mouse button. The button is pressed. The button is released. The following example shows a mouse event handler that determines which buttons are currently pressed by checking the button state of each mouse button. The MouseButtonState enumeration specifies constants which correlate to the state of a mouse button.
Microsoft makes no warranties, express or implied, with respect to the information provided here. Gets the state of the left button of the mouse. The state of the left mouse button.
The problem is you're trying to mix two GUI technologies: WinForms and WPF. You've set environment suitable for WinForms but trying to use methods from WPF.
You dont need PresentationCore.dll
and System.Windows.Input
. The desired result can be achieved using System.Windows.Forms.Control
class:
public static void ListenerThread()
{
while (true)
{
if ((Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left)
{
System.Diagnostics.Debug.WriteLine("Left mouse down");
}
Thread.Sleep(1000);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With