Mouse.LeftButton == MouseButtonState.Pressed永不返回true [英] Mouse.LeftButton == MouseButtonState.Pressed never returning true
问题描述
我在C#中有一个Windows窗体应用程序,它监视是否按住了鼠标按钮.GUI有一个主线程,它产生了一个辅助STA线程.此代码永远不会在其中执行:
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");
}
我想知道这是否是因为我为线程启用了以下STA选项吗?
I wondered if this is because I have the following STA option enabled for the thread?
repeaterThread.SetApartmentState(ApartmentState.STA);
repeaterThread.Start();
完整的相关代码:我正在使用 PresentationCore.dll
和 System.Windows.Input
;Winforms GUI:
Full relevant code:
I'm using PresentationCore.dll
, and System.Windows.Input
;
Winforms GUI:
按下启动按钮时:
...
Thread repeaterThread = new Thread(() => ListenerThread());
repeaterThread.SetApartmentState(ApartmentState.STA);
repeaterThread.Start();
...
ListenerThread方法:
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?
谢谢
推荐答案
问题是您要混合使用两种GUI技术:WinForms和WPF.您已经设置了适用于WinForms的环境,但是尝试使用WPF中的方法.
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.
您不需要 PresentationCore.dll
和 System.Windows.Input
.可以使用 System.Windows.Forms.Control
类实现所需的结果:
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);
}
}
这篇关于Mouse.LeftButton == MouseButtonState.Pressed永不返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!