2011-03-27 48 views
1

嘿,我有關鍵事件處理程序的一些問題。這是來源:C#檢測所有窗口中的關鍵事件

using System; 
     using System.Collections.Generic; 
     using System.ComponentModel; 
     using System.Data; 
     using System.Drawing; 
     using System.Linq; 
     using System.Text; 
     using System.Windows.Forms; 
     using System.Diagnostics; 
     using System.Threading; 

     namespace WindowsFormsApplication3 
     { 
      public partial class Form1 : Form 
      { 
       public Form1() 
       { 
        InitializeComponent(); 
       } 

       [System.Runtime.InteropServices.DllImport("user32.dll")] 
       public static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); 


     public const int MOUSEEVENTF_LEFTDOWN = 0x02; 
     public const int MOUSEEVENTF_LEFTUP = 0x04; 
     public const int MOUSEEVENTF_RIGHTDOWN = 0x08; 
     public const int MOUSEEVENTF_RIGHTUP = 0x10; 


       public void Form1_KeyPessed(object sender, KeyEventArgs e) 
       { 
        if (e.KeyCode == Keys.F2) 
        { 
         DrawSquare(); 
        } 
       } 

       public void DrawSquare() 
       { 
        int line = Convert.ToInt16(textBox1.Text); 
        int time = Convert.ToInt16(textBox2.Text); 

        int x = MousePosition.X; 
        int y = MousePosition.Y; 
        Cursor.Position = new Point(x - line/2, y - line/2); 
        mouse_event(MOUSEEVENTF_LEFTDOWN, x, y, 0, 0); 
        Thread.Sleep(time); 
        Cursor.Position = new Point(x - line/2, y + line/2); 
        Thread.Sleep(time); 
        Cursor.Position = new Point(x - line/2, y + line/2); 
        Thread.Sleep(time); 
        Cursor.Position = new Point(x + line/2, y - line/2); 
        Thread.Sleep(time); 
        Cursor.Position = new Point(x - line/2, y - line/2); 
        mouse_event(MOUSEEVENTF_LEFTUP, x, y, 0, 0); 
        Thread.Sleep(time); 
        Cursor.Position = new Point(x, y); 
       } 
      }  
     } 

現在它只繪製廣場,當我按F2在窗體中,但我希望它可以在所有窗口上工作。 我還需要什麼? (這是有點完美形狀的自動抽屜)

+1

有關[mouse_event'文檔](http://msdn.microsoft.com/zh-cn/library/ms646260.aspx)的注意事項。它說:**這個功能已被取代。請使用['SendInput'](http://msdn.microsoft.com/zh-cn/library/ms646310.aspx)** – 2011-03-27 16:05:01

+0

爲什麼要刪除我添加的標籤?更多標籤有助於對您的問題進行分類,以便其他人可以找到它。它還幫助回答問題的人找到它。他們通常會遵循他們熟悉的特定標籤。 – 2011-03-28 04:19:50

回答

2

如果您只想處理幾個組合鍵,則可以使用RegisterHotKey。如果您想檢測所有不同的按鍵事件,請使用the global hook as Paul suggested

+0

我以前沒有遇到過RegisterHotKey,但似乎這個用例更簡單的解決方案... – 2011-03-28 10:33:08

+0

@Paul:的確,確實如此。您的全球掛鉤解決方案非常出色,而且我一直都在使用。但是對於一個簡單的熱鍵,這有點像使用火箭筒來殺死蒼蠅。它會工作,但它確實是過度殺傷,並且實際上會損害整體性能。全局鉤子[應該真的很謹慎](http://msdn.microsoft.com/en-us/library/ms644959.aspx)。當然,Windows API非常大,我經常在回答問題時忘記了'RegisterHotKey' ... :-) – 2011-03-29 03:39:15

+0

您能舉個簡單的例子嗎? – giger 2011-03-29 17:21:28