2015-09-17 83 views
0

我正在使用Windows窗體工作我的項目,並需要模擬鼠標單擊。我從文本框中獲取座標,按下按鈕後,它必須進行雙擊,但不幸的是我沒有進行單擊。誰能說出原因?以下是一個代碼:模擬鼠標雙擊不起作用

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] 
     public static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo); 

     private const int MOUSEEVENT_LEFTDOWN = 0x0002; 
     private const int MOUSEEVENTF_LEFTUP = 0x0004; 
     private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; 
     private const int MOUSEEVENTF_RIGHTUP = 0x0010; 
     private const int MOUSEEVENTF_ABSOLUTE = 0x8000; 

     private void button2_Click(object sender, EventArgs e) 
     { 
      int x = Convert.ToInt32(textBox1.Text); 
      int y = Convert.ToInt32(textBox2.Text); 
       mouse_event(MOUSEEVENT_LEFTDOWN, x, y, 0, 0); 
       mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0); 
       mouse_event(MOUSEEVENT_LEFTDOWN, x, y, 0, 0); 
       mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0); 

     } 
+2

http://stackoverflow.com/questions/2416748/how-to-simulate-mouse-click-in-c –

+0

使用'NumericUpDown'輸入數字。 –

+0

btw,[''mouse_event''](https://msdn.microsoft.com/de-de/library/windows/desktop/ms646260(v = vs.85).aspx)不再受支持,請使用[ ''SendInput''](https://msdn.microsoft.com/de-de/library/windows/desktop/ms646310(v = vs.85).aspx)。 –

回答

0

根據This MSDN discussion您可能必須在點擊之間等待。

[DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)] 
public static extern void mouse_event(uint dwFlags, int dx, int dy, int dwData, int dwExtraInfo); 

private const int MOUSEEVENT_LEFTDOWN = 0x0002; 
private const int MOUSEEVENTF_LEFTUP = 0x0004; 
private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; 
private const int MOUSEEVENTF_RIGHTUP = 0x0010; 
private const int MOUSEEVENTF_ABSOLUTE = 0x8000; 

private void button2_Click(object sender, EventArgs e) 
{ 
    int x = Convert.ToInt32(textBox1.Text); 
    int y = Convert.ToInt32(textBox2.Text); 
    mouse_event(MOUSEEVENT_LEFTDOWN, x, y, 0, 0); 
    mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0); 
    Thread.Sleep(50); 
    mouse_event(MOUSEEVENT_LEFTDOWN, x, y, 0, 0); 
    mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0); 
}