开发者

C# detecting key event in all windows

Hey, i have some problem with key event handler. This is source:

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.Sl开发者_开发技巧eep(time);
                    Cursor.Position = new Point(x, y);
                }
            }      
        }

Now it only draws square when i press F2 in form, but i want it to work on all windows. What should i need more? (this is kinda auto drawer for perfect shapes)


If you only want to handle a couple key combinations, you can use RegisterHotKey. If you want to detect all different key events, go with the global hook as Paul suggested.


You need a global hook. There's a brilliant implementation here http://www.codeproject.com/KB/cs/globalhook.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜