2011-11-26 3 views
1

다른 응용 프로그램에서 사용자가 누른 키를 얻고 싶습니다. 예를 들어 메모장에서는 프로그램 자체가 아닙니다. 여기 내 코드는 PostMessage을 사용하여 메모장에 키를 계속 전송하지만 일부 키를 누를 때 중지하고 싶습니다. 사용자가 메모장에서 X 키를 누르면다른 응용 프로그램에서 키 누르기 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);                
      } 
     } 
    } 
} 

따라서, 내 생각은 falseControlKeyDown 설정됩니다. 인터넷을 통해 조사 후, 나는이 코드를 발견하고 편집 :

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

예, 이것에 의해, 그것은 확실히 루핑을 중지하지만 이것은 루프를 중지하므로 사용자가에 X 키를 누를 때 내가 원하는하지 않습니다 프로그램은 있지만 메모장에는 없습니다. 이는 KeyEventArgs이 메모장이 아닌 System.Windows.Forms.KeyEventArgs이기 때문입니다.

, 그것은 C++입니다 See this article. 난 당신이 키보드 후킹을 찾고있는 것 같아요

답변

2

:(도움이 필요하지만 페이지에 민첩 것으로 보인다/그래서 호출 당신은 아마 얼마나 쉽게 포트를합니다.

+0

확인 덕분에, 나는에 세부 사항을 볼 것이다. – Momo

0

당신은 USER32.DLL에서 SetWindowsHookEx 기능을 살펴 할 수 있습니다.

나는 또한 사용자가 gma.UserActivity 라이브러리 프로젝트에서 그것을 할 수 있습니다.