Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Mouse.LeftButton==MouseButtonState.按下后将永远不会返回true_C#_.net_Winforms - Fatal编程技术网

C# Mouse.LeftButton==MouseButtonState.按下后将永远不会返回true

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

我有一个C语言的Windows窗体应用程序,它监视鼠标按钮是否被按下。GUI有一个主线程,它生成一个辅助STA线程。此代码从不在其中执行:

 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()总是在创建线程之前发生。这可能是问题所在吗?好的,解决了,抱歉,你的控制建议。鼠标按钮第一次起作用。我只是把代码弄乱了。我没有找到正确的代码路径。非常感谢,标记为答案!