C# Mouse.LeftButton==MouseButtonState.按下后将永远不会返回true
我有一个C语言的Windows窗体应用程序,它监视鼠标按钮是否被按下。GUI有一个主线程,它生成一个辅助STA线程。此代码从不在其中执行:C# Mouse.LeftButton==MouseButtonState.按下后将永远不会返回true,c#,.net,winforms,C#,.net,Winforms,我有一个C语言的Windows窗体应用程序,它监视鼠标按钮是否被按下。GUI有一个主线程,它生成一个辅助STA线程。此代码从不在其中执行: if (Mouse.LeftButton == MouseButtonState.Pressed) { System.Diagnostics.Debug.WriteLine("Left mouse down"); } 我想知道这是否是因为我为线程启用了以下STA选项 repeaterThread.SetApartmentState(Apar
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
System.Diagnostics.Debug.WriteLine("Left mouse down");
}
我想知道这是否是因为我为线程启用了以下STA选项
repeaterThread.SetApartmentState(ApartmentState.STA);
repeaterThread.Start();
完整相关代码:
我正在使用PresentationCore.dll
和System.Windows.Input
;
Winforms GUI:
按下启动按钮时:
...
Thread repeaterThread = new Thread(() => ListenerThread());
repeaterThread.SetApartmentState(ApartmentState.STA);
repeaterThread.Start();
...
ListenerThread方法:
public static void ListenerThread()
{
while(true)
{
if (Mouse.LeftButton == MouseButtonState.Pressed)
{
System.Diagnostics.Debug.WriteLine("Left mouse down");
}
Thread.sleep(1000);
}
}
如何捕获鼠标按钮是否从该线程按下
谢谢问题是您试图混合使用两种GUI技术:WinForms和WPF。您已经设置了适合WinForms的环境,但尝试使用WPF中的方法 您不需要
PresentationCore.dll
和System.Windows.Input
。可以使用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);
}
}
您是否尝试在循环之前调用
Application.Run()
内部ListenerThread()
?只是尝试了一下,没有成功。Run()上的上下文为空,对吗?是。您在没有参数的情况下调用Run()来启动当前线程的消息循环是的,我尝试过,但没有成功:(鼠标类需要WPF dispatcher循环来提供准确的信息。这里的诊断是您的应用程序运行Winforms dispatcher循环。换句话说,错误的应用程序。Run()。交换它不是解决方案,现在Winforms变得不稳定,例如,您会注意到导航键和快捷键不再工作。在多个线程上显示UI通常也是一个相当糟糕的主意,您需要进行调试。刚刚测试过这一点,它就不起作用了。我正在按照您的建议使用System.Windows.Forms.Control,复制并粘贴它您的代码完全正确。在这里工作正常。也许您在线程睡眠时按下鼠标?并确保在调用应用程序之前启动线程。Run()
被称为dhmm,我的线程是在表单类中创建和启动的,因此当用户按下按钮时,它会从:Form类创建和启动线程(即背后的GUI代码)。因此应用程序.Run()总是在创建线程之前发生。这可能是问题所在吗?好的,解决了,抱歉,你的控制建议。鼠标按钮第一次起作用。我只是把代码弄乱了。我没有找到正确的代码路径。非常感谢,标记为答案!