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.Runtime.InteropServices;
using System.Threading;

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

        #region AIP

        //如果函数执行成功,返回值不为0。
        //如果函数执行失败,返回值为0。要得到扩展错误信息,调用GetLastError。
        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool RegisterHotKey(
            IntPtr hWnd,                //要定义热键的窗口的句柄
            int id,                     //定义热键ID(不能与其它ID重复)
            KeyModifiers fsModifiers,   //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效
            Keys vk                     //定义热键的内容
            );

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool UnregisterHotKey(
            IntPtr hWnd,                //要取消热键的窗口的句柄
            int id                      //要取消热键的ID
            );

        //定义了辅助键的名称(将数字转变为字符以便于记忆,也可去除此枚举而直接使用数值)
        [Flags()]
        public enum KeyModifiers
        {
            None = 0,
            Alt = 1,
            Ctrl = 2,
            Shift = 4,
            WindowsKey = 8
        }

        //获取鼠标当前位置
        [DllImport("user32.dll")]
        private static extern bool GetCursorPos(out Point p);

        //设置鼠标位置
        [DllImport("User32")]
        public extern static void SetCursorPos(int x, int y);

        //模拟鼠标
        [DllImport("User32")]
        public extern static void mouse_event(int dwFlags, int dx, int dy, int dwData, IntPtr dwExtraInfo);

        public enum MouseEventFlags
        {
            Move = 0x0001, //移动鼠标
            LeftDown = 0x0002,//模拟鼠标左键按下
            LeftUp = 0x0004,//模拟鼠标左键抬起
            RightDown = 0x0008,//鼠标右键按下
            RightUp = 0x0010,//鼠标右键抬起
            MiddleDown = 0x0020,//鼠标中键按下
            MiddleUp = 0x0040,//中键抬起
            Wheel = 0x0800,
            Absolute = 0x8000//标示是否采用绝对坐标
        }

        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            RegisterHotKey(Handle, 100, KeyModifiers.None, Keys.F7);//F7 锁定消息框位置
            RegisterHotKey(Handle, 101, KeyModifiers.None, Keys.F8);//F8 开始 / 暂停
            RegisterHotKey(Handle, 102, KeyModifiers.None, Keys.F9);//F9 隐藏 / 显示

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            if (MessageBox.Show("你是否要退出?","退出提示",MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK)
            {
                e.Cancel = false;
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            UnregisterHotKey(Handle, 100);
            UnregisterHotKey(Handle, 101);
            UnregisterHotKey(Handle, 102);
        }

        protected override void WndProc(ref Message m)
        {
            const int WM_HOTKEY = 0x0312;
            //按快捷键
            switch (m.Msg)
            {
                case WM_HOTKEY:
                    switch (m.WParam.ToInt32())
                    {
                        case 100:    // F7 锁定位置
                            FindPoint();
                            break;
                        case 101:    //F8 开始 / 暂停
                            MakeStart();
                            break;
                        case 102:    //F9 隐藏 / 显示
                            MakeShow();
                            break;
                    }
                    break;
            }
            base.WndProc(ref m);
        }

        Point CP = new Point();

        //寻找位置
        private void FindPoint()
        {
            GetCursorPos(out CP);
            label5.Text = "(" + CP.X + " , "+ CP.Y + ")";
        }
        //开始/暂停
        private void MakeStart()
        {
            int t_interval = 0;
            int.TryParse(textBox2.Text.ToString(), out t_interval);
            if (t_interval < 100)
            {
                t_interval = 100;
            }
            timer1.Interval = t_interval;
            timer1.Enabled = !timer1.Enabled;
        }
        //隐藏/显示
        private void MakeShow()
        {
            this.Visible = !this.Visible;
        }

        int indexs = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            indexs++;
            SendMessage();
        }
        //发送消息
        [DllImport("user32.dll", EntryPoint = "keybd_event", SetLastError = true)]
        public static extern void keybd_event(Keys bVk, byte bScan, uint dwFlags, uint dwExtraInfo);
        public const int WM_KEYDOWN = 256;
        public const int WM_KEYUP = 257;

        private void SendMessage()
        {
            if (textBox1.Text.ToString() != "")
            {
                MoveMouse();
                DoubleMouse();
                //Thread.Sleep(100);

                keybd_event(Keys.ControlKey, 0, 0, 0);
                keybd_event(Keys.A, 0, 0, 0);
                keybd_event(Keys.A, 0, 0x2, 0);
                keybd_event(Keys.ControlKey, 0, 0x2, 0);

                Thread.Sleep(10);

                SendKeys.SendWait(textBox1.Text.ToString());
                SendKeys.SendWait("{ENTER}");
            }
        }
        //移动鼠标
        private void MoveMouse()
        {
            SetCursorPos(CP.X, CP.Y);
        }
        //双击鼠标
        private void DoubleMouse()
        {
            mouse_event((int)(MouseEventFlags.LeftDown | MouseEventFlags.Absolute), 0, 0, 0, IntPtr.Zero);
            mouse_event((int)(MouseEventFlags.LeftUp | MouseEventFlags.Absolute), 0, 0, 0, IntPtr.Zero);

            //mouse_event((int)(MouseEventFlags.LeftDown | MouseEventFlags.Absolute), 0, 0, 0, IntPtr.Zero);
            //mouse_event((int)(MouseEventFlags.LeftUp | MouseEventFlags.Absolute), 0, 0, 0, IntPtr.Zero);
        }
    }
}

时间: 2024-08-10 15:20:44

C# 定义热键的相关文章

C# 注册 Windows 热键

原文:C# 注册 Windows 热键 闲扯: 前几日,一个朋友问我如何实现按 F1 键实现粘贴(Ctrl+V)功能,百度了一个方法,发给他,他看不懂(已经是 Boss 的曾经的码农),我就做了个Demo给他参考.今日得空,将 Demo 整理一下,做为收集,也给大家一个参考. Begin: 注册系统热键,.net 类库好像没有提供现成的方法,需要使用系统提供的 DLL. 微软将许多常用的系统函数都封装在 user32.dll 中,注册系统热键使用到的 RegisterHotKey 函数和 Unr

WinForm和WPF中注册热键

由于.Net没有提供专门的类库处理热键,所以需要直接调用windows API来解决. HotKey为.NET调用Windows API的封装代码,主要是RegisterHotKey和UnregisterHotKey class HotKey { /// <summary> /// 如果函数执行成功,返回值不为0. /// 如果函数执行失败,返回值为0.要得到扩展错误信息,调用GetLastError..NET方法:Marshal.GetLastWin32Error() /// </su

C# 全局热键设置 与 窗体热键设置

1. 窗体热键 首先要设置主窗体KeyPreview为true,可直接在属性中进行设置, 或者在窗体加载中设置: this.KeyPreview = true; 然后添加窗体KeyDown事件,如下: private void FrmMain_KeyDown(object sender, KeyEventArgs e) { if (e.Alt && e.Shift && e.Control && e.KeyCode == Keys.S) { MessageB

Java设置全局热键——第三方包jintellitype实现

Java原生API并不支持为应用程序设置全局热键.要实现全局热键,需要用JNI方式实现,这就涉及到编写C/C++代码,这对于大多数不熟悉C/C++的javaer来说,有点困难.不过幸好,国外有人已经实现了,发布成第三方java包,借此,我们可以很方便的设置全局热键而不用编写任何C/C++代码. jintellitype官网貌似目前访问不到,这里提供下载:http://pan.baidu.com/s/1kTIDxgN. 我实现的演示Demo源码下载:http://pan.baidu.com/s/1

wpf程序热键的一个类

using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Forms; using System.Windows.Interop; namespace WpfHot

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.Runtime.InteropServices; namespace OpenMonitor{    public par

Windows热键注册的底层原理

要像系统注册一个全局热键,需要用到RegisterHotKey,函数用法如下(MSDN):BOOL RegisterHotKey(                                                HWND hWnd,                                          int id,                                          UINT fsModifiers,                   

作个有安全感的应用,告别裸奔

自个对架构比较感兴趣.闲暇时间学习学习相关姿势,也涨涨姿势. 算是自娱自乐也算是实践吧!把自己平时用的小功能做了个系统都算不上的小应用吧! 一开始通过账号密码验证,然后加上了,mac地址验证还是觉得不够安全,最近把数字证书的功能也加上了,感觉小有有点安全感,不再裸奔了.可以跟大家分享分享. 1.浅说架构 这样一个拓扑图,大家首先想到的是bs的网站吧!其实我们今天说的cs架构的小应用. 使用wcf支撑的soa架构: 为什么用wcf呢?首先wcf简单上手快,然后wcf我可以通过简单的配置实现用htt

北京天宇联科技有限责任公司—T语言Ios开发命名规范

T语言(ttyu software language )是一种通过定义的方式自动生成原生态的android.ios和自适应各浏览的h5的web页面的三合一的软件开发语言.T语言是一种简单的,易于使用的开发软件.T语言运用TC简单开发. TC简单开发是国内首款免费多线程的图形界面脚本制作开发工具软件,支持中英文双语言编写脚本程序,综合脚本开发工具,可以说TC开脚本界先河,是免费脚本开发制作工具的首选.通过制作脚本,可以让TC简单开发代替您的双手,自动执行一系列鼠标键动作.能陪伴你每日每夜的脚本开发