2011-11-26 44 views
1

我想獲取用戶在其他應用程序上按下的按鍵。例如,在記事本中,而不是程序本身。這裏是我的編碼,使用PostMessage方法連續發送鍵到記事本,但是,我希望當按下某個鍵時停止它。從其他應用程序獲取密鑰C#

using System.Diagnostics; 
using System.Runtime.InteropServices; 
using System.Threading; 

     [DllImport("user32.dll")] 
public static extern IntPtr FindWindow(
    string ClassName, 
    string WindowName); 

[DllImport("User32.dll")] 
public static extern IntPtr FindWindowEx(
    IntPtr Parent, 
    IntPtr Child, 
    string lpszClass, 
    string lpszWindows); 

[DllImport("User32.dll")] 
public static extern Int32 PostMessage(
    IntPtr hWnd, 
    int Msg, 
    int wParam, 
    int lParam); 

private const int WM_KEYDOWN = 0x100; 

public Form1() 
{ 
    InitializeComponent(); 
} 

private void button1_Click(object sender, EventArgs e) 
{ 
    Thread t = new Thread(new ThreadStart(Test)); 
    t.Start(); 
} 

Boolean ControlKeyDown = true; 

public void Test() 
{ 
    // retrieve Notepad main window handle 
    IntPtr Notepad = FindWindow("Notepad", "Untitled - Notepad"); 

    if (!Notepad.Equals(IntPtr.Zero)) 
    { 
     // retrieve Edit window handle of Notepad 
     IntPtr Checking = FindWindowEx(Notepad, IntPtr.Zero, "Edit", null); 

     if (!Checking.Equals(IntPtr.Zero)) 
     { 

      while (ControlKeyDown) 
      {       
       Thread.Sleep(100); 

       PostMessage(Checking, WM_KEYDOWN, (int)Keys.A, 0);                
      } 
     } 
    } 
} 

因此,當用戶按下在記事本中X鑰匙我的想法是設置ControlKeyDownfalse。通過互聯網研究之後,我發現這個代碼和編輯:

protected override void OnKeyDown(KeyEventArgs kea) 
{ 
    if (kea.KeyCode == Keys.X) 
    ControlKeyDown = false; 
} 

是的,這一點,它肯定會停止循環,但是這不是我想要的,因爲它會導致循環停止,當用戶按下X關鍵程序,但不在記事本中。這是因爲KeyEventArgsSystem.Windows.Forms.KeyEventArgs而不是記事本。

需要幫助:(

回答

2

我猜你正在尋找鍵盤掛鉤。See this article,它是C++,但你似乎是P中敏捷/調用,所以你可能會得到如何輕鬆地將它。

+0

好,謝謝,我會看對細節。 – Momo

相關問題