Reputation: 1274
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
Upvotes: 5
Views: 8127
Reputation: 814
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);
}
}
Upvotes: 9