【问题标题】:Detect left mouse button down after sending left mouse button up向上发送鼠标左键后检测鼠标左键向下
【发布时间】:2017-09-30 12:32:36
【问题描述】:

我正在编写一个程序来扫描鼠标左键是否被按住,然后向上发送鼠标左键并在此之后继续。问题是,由于我向上发送鼠标左键,程序将无法继续,因为鼠标左键不再被按住。

这是一些伪代码:

if(GetKeyState(VK_LBUTTON) < 0){
   Sleep(10);
   mouse_event(MOUSEEVENTF_LEFTUP, p.x, p.y, 0, 0);
   //Rest of code
}

在此之后如何检测鼠标左键被按下?我必须使用驱动程序吗?

【问题讨论】:

  • “程序将不会继续,因为鼠标左键不再被按住”我不关注。
  • 它仍然被物理鼠标按住,我想知道如何检测物理鼠标按钮被按住。
  • 不要发送MOUSEEVENTF_LEFTUP。
  • 这是我正在做的事情的一部分。我需要发送它。
  • 什么原因?

标签: c++ windows


【解决方案1】:

通过阅读您对程序的描述,只有这里是我的实现。 使用 Windows API:

while (true) {
     //check if left mouse button is down
     if (GetKeyState(VK_LBUTTON) & 0x8000) {
         //send left mouse button up
         //You might want to place a delay in here
         //to simulate the natural speed of a mouse click
         //Sleep(140);

         INPUT    Input = { 0 };
         ::ZeroMemory(&Input, sizeof(INPUT));
         Input.type = INPUT_MOUSE;
         Input.mi.dwFlags = MOUSEEVENTF_LEFTUP;
         ::SendInput(1, &Input, sizeof(INPUT));
     }
}

如果你想在强制阻止人们点击和拖动的同时做其他事情,你可以将此代码放入一个你在线程中调用的函数中。

void noHoldingAllowed() {
     //insert code here used above...
 }

 int main(void) {
  std::thread t1(noHoldingAllowed);
  //other stuff...

  return 0;
{

【讨论】:

    【解决方案2】:

    只需使用一个标志:

    bool lButtonWasDown=flase;
    
    if(GetKeyState(VK_LBUTTON) < 0){
       Sleep(10);
       lButtonWasDown = true;
       mouse_event(MOUSEEVENTF_LEFTUP, p.x, p.y, 0, 0);
    } 
    
    if (lButtonWasDown)
    {
      // rest of the code for lButtonWasDown = true
    }
    

    【讨论】:

      【解决方案3】:

      我没有测试过这段代码,但它应该可以工作

      while(programIsRunning)
      {
         if(GetKeyState(VK_LBUTTON) < 0){
         Sleep(10);
         mouse_event(MOUSEEVENTF_LEFTUP, p.x, p.y, 0, 0);
         // rest of the code
      }
      

      它应该可以工作,因为如果在循环重新运行时按住 Lmouse 按钮​​ if 将触发 if 语句,然后将触发 mouseup 事件。

      注意: 你也许可以做到while(GetKeyState(VK_LBUTTON) &lt; 0){//code here}

      【讨论】:

      • if(GetKeyState(VK_LBUTTON) &lt; 0) 已经在 while(1) 循环中。我尝试了while(GetKeyState(VK_LBUTTON) &lt; 0),但没有奏效,与 if 语句一样。
      • 你如何处理 mouseUp 事件?
      • 我不确定你的意思,我只想发送 mouseUp 并且仍然运行其余的 if 语句。
      猜你喜欢
      • 2011-04-26
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      相关资源
      最近更新 更多