2011-03-27 9 views
1

안녕하세요, 키 이벤트 처리기에 문제가 있습니다. 이 소스 : 난 형태로 F2 키를 누르면모든 창에서 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); 
       } 
      }  
     } 

는 이제 만 평방립니다,하지만 난이 모든 창에 작업 할. 더 필요한 것이 있습니까? (완벽한 모양의 자동 서랍)

+1

[mouse_event]에 대한 문서 (http://msdn.microsoft.com/en-us/library/ms646260.aspx)에 흥미로운 점이 있습니다. 그것은 말한다 : **이 기능은 대체되었습니다. 대신 ['SendInput'] (http://msdn.microsoft.com/en-us/library/ms646310.aspx)를 사용하십시오 ** –

+0

왜 내가 추가 한 태그를 제거 했습니까? 다른 태그를 사용하면 질문을 분류하여 다른 사람들이 찾을 수 있습니다. 또한 질문에 대답하는 사람들이 그것을 찾는데 도움이됩니다. 그들은 종종 지식이있는 특정 태그를 따릅니다. –

답변

2

몇 가지 키 조합 만 처리하려는 경우 RegisterHotKey을 사용할 수 있습니다. 다른 모든 키 이벤트를 감지하려면 the global hook as Paul suggested으로 이동하십시오.

+0

전에 RegisterHotKey를 사용하지는 않았지만이 방법은 훨씬 간단합니다. –

+0

@Paul : 예, 실제로. 귀사의 글로벌 후크 솔루션은 탁월한 솔루션이며, 항상 제가 사용하는 솔루션입니다. 그러나 간단한 단축키는 파리를 죽이기 위해 바주카포를 사용하는 것과 조금 비슷합니다. 그것은 효과가있을 것이다. 그러나 그것은 과잉 공격이며 실제로 전반적인 성능을 해칠 것이다. 글로벌 후크 [정말 아껴서 사용해야합니다] (http://msdn.microsoft.com/en-us/library/ms644959.aspx) 물론 Windows API가 너무 커서 자신에게 질문에 대답 할 때 자주 RegisterHotKey를 잊을 수 있습니다. :-) –

+0

간단한 예제를 만들 수 있습니까? – giger