C# winform 程序在后台运行 点击快捷键使程序做出相应反应。

作者&投稿:巩符 (若有异议请与网页底部的电邮联系)
C# WinForm如何实现全局快捷键?~

这是个封装好的类,非常好用,不懂怎么使用可以百度给我发消息
using System;
using System.Runtime.InteropServices;

namespace SystemHotKey
{

public delegate void HotkeyEventHandler(int HotKeyID);

public class Hotkey : System.Windows.Forms.IMessageFilter

{

System.Collections.Hashtable keyIDs = new System.Collections.Hashtable();

IntPtr hWnd;


public event HotkeyEventHandler OnHotkey;


public enum KeyFlags

{


MOD_ALT = 0x1,


MOD_CONTROL = 0x2,


MOD_SHIFT = 0x4,


MOD_WIN = 0x8

}

[DllImport("user32.dll")]

public static extern UInt32 RegisterHotKey(IntPtr hWnd, UInt32 id, UInt32 fsModifiers, UInt32 vk);


[DllImport("user32.dll")]

public static extern UInt32 UnregisterHotKey(IntPtr hWnd, UInt32 id);


[DllImport("kernel32.dll")]

public static extern UInt32 GlobalAddAtom(String lpString);


[DllImport("kernel32.dll")]

public static extern UInt32 GlobalDeleteAtom(UInt32 nAtom);


public Hotkey(IntPtr hWnd)

{


this.hWnd = hWnd;


System.Windows.Forms.Application.AddMessageFilter(this);

}


public int RegisterHotkey(System.Windows.Forms.Keys Key, KeyFlags keyflags)

{


UInt32 hotkeyid = GlobalAddAtom(System.Guid.NewGuid().ToString());


RegisterHotKey((IntPtr)hWnd, hotkeyid, (UInt32)keyflags, (UInt32)Key);


keyIDs.Add(hotkeyid, hotkeyid);


return (int)hotkeyid;

}


public void UnregisterHotkeys()

{


System.Windows.Forms.Application.RemoveMessageFilter(this);


foreach (UInt32 key in keyIDs.Values)


{



UnregisterHotKey(hWnd, key);



GlobalDeleteAtom(key);


}

}


public bool PreFilterMessage(ref System.Windows.Forms.Message m)

{


if (m.Msg == 0x312)


{



if (OnHotkey != null)



{




foreach (UInt32 key in keyIDs.Values)




{





if ((UInt32)m.WParam == key)





{





OnHotkey((int)m.WParam);





return true;





}




}



}


}


return false;

}

}
}

如果没有报错的话.看看是不是内存不够.或者系统的类库不足.例如你调用COM组件.
引用了其他的DLL等等.都是可能存在的问题

如果没有报错的话.看看是不是内存不够.或者系统的类库不足.例如你调用COM组件.引用了其他的DLL等等.都是可能存在的问题。

对这个需求完全可以在单击“关闭”按钮的时候弹出一个对话框,来让用户确定是否真的要退出。这是一个很好的解决方法,并且实现也是很容易的。但是人家不想这样,想要拥有类似QQ在托盘区后台运行的那种效果,没办法,只能想办法来实现了。www.2cto.com
 
.
 
[csharp]
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.Windows;  
  
  
namespace winform窗体托盘后台运行  
{  
    public partial class Form1 : Form   
    {  
        //这里在窗体上没有拖拽一个NotifyIcon控件,而是在这里定义了一个变量  
        private NotifyIcon notifyIcon = null;  
  
        public Form1()  
        {  
            InitializeComponent();  
            //调用初始化托盘显示函数  
            InitialTray();  
        }  
  
        private void Form1_Load(object sender, EventArgs e)  
        {  
            //这里写其他代码  
        }  www.2cto.com
  
        /// <summary>  
        /// 窗体关闭的单击事件  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)  
        {  
            e.Cancel = true;  
            //通过这里可以看出,这里的关闭其实不是真正意义上的“关闭”,而是将窗体隐藏,实现一个“伪关闭”  
            this.Hide();  
        }  
  
        private void InitialTray()  
        {  
            //隐藏主窗体  
            this.Hide();  
  
            //实例化一个NotifyIcon对象  
            notifyIcon = new NotifyIcon();  
            //托盘图标气泡显示的内容  
            notifyIcon.BalloonTipText = "正在后台运行";     
            //托盘图标显示的内容  
            notifyIcon.Text = "窗体托盘后台运行测试程序";  
            //注意:下面的路径可以是绝对路径、相对路径。但是需要注意的是:文件必须是一个.ico格式  
            notifyIcon.Icon = new System.Drawing.Icon("E:/ASP项目/images/3.5 inch Floppy.ico");  
            //true表示在托盘区可见,false表示在托盘区不可见  
            notifyIcon.Visible = true;  
            //气泡显示的时间(单位是毫秒)  
            notifyIcon.ShowBalloonTip(2000);              
            notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick);  
              
            ////设置二级菜单  
            //MenuItem setting1 = new MenuItem("二级菜单1");  
            //MenuItem setting2 = new MenuItem("二级菜单2");  
            //MenuItem setting = new MenuItem("一级菜单", new MenuItem[]{setting1,setting2});  
  
            //帮助选项,这里只是“有名无实”在菜单上只是显示,单击没有效果,可以参照下面的“退出菜单”实现单击事件  
            MenuItem help = new MenuItem("帮助");  
  
            //关于选项  
            MenuItem about = new MenuItem("关于");  
  
            //退出菜单项  
            MenuItem exit = new MenuItem("退出");  
            exit.Click += new EventHandler(exit_Click);  
  
            ////关联托盘控件  
            //注释的这一行与下一行的区别就是参数不同,setting这个参数是为了实现二级菜单  
            //MenuItem[] childen = new MenuItem[] { setting, help, about, exit };  
            MenuItem[] childen = new MenuItem[] {help,about,exit};  
            notifyIcon.ContextMenu = new ContextMenu(childen);  
  
            //窗体关闭时触发  
            this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.Form1_FormClosing);  
        }  
        
        /// <summary>  
        /// 鼠标单击  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void notifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)  
        {  
            //鼠标左键单击  
            if (e.Button == MouseButtons.Left)  
            {  
                //如果窗体是可见的,那么鼠标左击托盘区图标后,窗体为不可见  
                if (this.Visible == true )  
                {  
                    this.Visible = false;  
                }  
                else  
                {  
                    this.Visible = true;  
                    this.Activate();  
                }  
            }  
        }  
  
        /// <summary>  
        /// 退出选项  
        /// </summary>  
        /// <param name="sender"></param>  
        /// <param name="e"></param>  
        private void exit_Click(object sender, EventArgs e)  
        {  
            //退出程序  
           System.Environment.Exit(0);    
        }  
    }  
}


        //初始化函数里加入以下两条就可以用了,我现在定义的是ALT+X与ALT+S
        //这两种组合键,你自己可以改
        public Frmain()
        {
            InitializeComponent();
            RegisterHotKey(this.Handle, 10, MODKEY.ALT, Keys.X);
            RegisterHotKey(this.Handle, 11, MODKEY.ALT, Keys.S);
        }
        protected override void WndProc(ref Message m)
        {
            if(m.Msg == 0x0312)
            {
                switch (m.WParam.ToInt32())
                {
                    case 10:
                        退出ToolStripMenuItem_Click(null,null);
                        break;
                    case 11:
                        notifyIcon1_Click(null,null);
                        break;
                    default:
                        break;
                }
                return;
            }
            base.WndProc(ref m);
        }

        //要定义热键的窗口的句柄
        //定义热键ID(不能与其它ID重复)int id, 
        //标识热键是否在按Alt、Ctrl、Shift、Windows等键时才会生效KeyModifiers fsModifiers,                 Keys vk                     //定义热键的内容
        [DllImport("user32.dll")]
        public static extern bool RegisterHotKey(IntPtr wnd, int id, MODKEY mode, Keys vk);

        [DllImport("user32.dll")]
        public static extern bool UnregisterHotKey(IntPtr wnd, int id);

        [Flags()]
        public enum MODKEY
        {
            None = 0,
            ALT = 0x0001,
            CTRL = 0x0002,
            SHIFT = 0x0004,
            WIN = 0x0008,
        }

刚好写完现成的。还热着呢,给你了,试过可用了。不过不能开同个窗口或是与这热键有冲突的程序。要不然会有其中的一个程序会没有响应的



热键是在界面不在后台的情况下使用的 你应该是用windows消息回调函数来判断按下了组合键没有

1、向Windows窗口发送Alt组合键
先看WM_SYSKEYDOWN的help:The WM_SYSKEYDOWN message is posted to the window with the keyboard focus when the user holds down the ALT key and then presses another key. It also occurs when no window currently has the keyboard focus; in this case, the WM_SYSKEYDOWN message is sent to the active window. The window that receives the message can distinguish between these two contexts by checking the context code in the lKeyData parameter.WM_SYSKEYDOWN nVirtKey = (int) wParam; // virtual-key code lKeyData = lParam; // key data ParametersnVirtKeyValue of wParam. Specifies the virtual-key code of the key being pressed. lKeyDataValue of lParam. Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag, as shown in the following table:Value Description0-15 Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user holding down the key.16-23 Specifies the scan code. The value depends on the original equipment manufacturer (OEM).24 Specifies whether the key is an extended key, such as the right-hand ALT and CTRL keys that appear on an enhanced 101- or 102-key keyboard. The value is 1 if it is an extended key; otherwise, it is 0.25-28 Reserved; do not use.29 Specifies the context code. The value is 1 if the ALT key is down while the key is pressed; it is 0 if the WM_SYSKEYDOWN message is posted to the active window because no window has the keyboard focus.30 Specifies the previous key state. The value is 1 if the key is down before the message is sent, or it is 0 if the key is up.31 Specifies the transition state. The value is always 0 for a WM_SYSKEYDOWN message.之前曾经修改过keyData的16-23位为VK_MENU,第30位参数为1,但没效果请看位29的说明!!The value is 1 if the ALT key is down while the key is pressed; 当值为1时表示ALT键被按下!这不正是我需要的吗?于是把29位设置为1,函数调用变成PostMessage(hWnd,WM_SYSKEYDOWN,0x41,1<<29);经过测试,发现这个就是Alt+A的效果!!

数学中C是什么意思???
答:C表示的是组合意思。组合(combination)是一个数学名词。从n个不同的元素中,任取m(m≤n)个元素为一组,叫作从n个不同元素中取出m个元素的一个组合。例如下题:有足够多的3,4,5,6,7米长的木材,取三根组成三角形,请问能组成多少个不同三角形?计算方法:C右上角是3,右下角是5,就是说...

c的意思?
答:C是发生事故的严重性,consequences的缩写。consequences 英 ['kɑnsə,kwɛnsɪz] 美 ['kɑnsə,kwɛnsɪz]n. 后果,结果;影响(consequence的复数)短语:unintended consequences 意外后果 ; 非预期后果 ; 未预期的后果 ; 没有预计的结果 serious consequences...

女生发个c是什么意思啊
答:女生发个c是什么意思啊 随着时代的发展,女性思想发生了翻天覆地的变化,过去女靠男,现在女性则崇尚独立,以下我为大家分享女生发个c是什么意思啊,快来看看吧 女生发个c是什么意思啊1 c的意思是 娘 就是说人 默默唧唧 不太爷们 形容词,c即cissy,而cissy=sissy,sissy意为柔弱或怯弱的男孩、...

c开头是什么车
答:C字头的列车是城际动车组列车。城际列车,又称城际专列(Inter-City Rail Service),是指往返于相邻重要城市或城市群之间的客运列车,一般全程运行距离较近、乘车时间较短、途经城市较少,不配置卧铺车厢。和谐号动车的车型,由原来的动车型号D改为C,并将其命名为城际轻轨。 (G字头车次是指高铁)高铁...

c是什么?
答:化学中C表示物质的量浓度(摩尔浓度),是一种常用的溶液浓度的表示方法,为溶液中溶质的物质的量除以混合物的体积。以上面公式中,C(B)代表溶质的物质的量浓度,n(B)代表溶质的物质的量,V代表溶液的体积。溶液浓度可分为质量浓度(如质量百分浓度)、体积浓度(如摩尔浓度、当量浓度)和质量-体积...

英语里[C],[C,U]代表什么意思?
答:[C]是可数名词,一般包括个体名词和集体名词,来源于单词count(可数的)[U]是不可数名词,一般包括物质名词和抽象名词,来源于单词uncount(不可数的)[C,U]表示此名词既可以做可数名词也可以做不可数名词。名词根据其可数性可分为可数名词(Countable Noun)和不可数名词(Uncountable Noun)。可数名词即指...

C是什么意思?
答:C表示组合数。C(n,m) 表示n选m的组合数,其中n是下标 , m是上标 (C上面m,下面n)。nCk是一个整体,是n个元素中,取k个元素的取法的个数,也叫n个元素中,取k 个k组合数,(C代表组合),算法是:nCk=n!/k!(n-k)!=n(n-1)……(n-k+1)/k!等于从n开始连续递减的m个自然...

c在爱情的含义
答:c在爱情的含义 c在爱情的含义。在日常生活中,很多人都是非常在乎一些关于爱情的含义的,c这个字母在爱情也具有着一定的解析。那么下面就为大家分享c在爱情的含义的相关内容。c在爱情的含义1 “C型爱情观”指的是对现代爱情关一种新的定义。在爱情中,有进有退、牵手分手的循环,已不再是个稀奇...

网络上C和sc是什么意思?
答:1、”C“是拼音“chu”的首字母,为了方便起见缩写为“C”,指的是处男、处女的意思。2、SC是superchat的缩写,是付费留言功能。这个功能最开始是YouTube2017年上线的,B站也推出了这个功能。这是一种在直播过程中连接粉丝与主播的方式,同时也可给主播带来相应的经济收益。通过这一功能,粉丝可以以明亮...

c的公式是什么?
答:m>n。排列组合c的公式:C(n,m)=A(n,m)/m!=n!/m!(n-m)!与C(n,m)=C(n,n-m)。(n为下标,m为上标)。例如C(4,2)=4!/(2!*2!)=4*3/(2*1)=6,C(5,2)=C(5,3)。排列组合c计算方法:C是从几个中选取出来,不排列,只组合。C(n,m)=n*(n-1)*...*(n-m+1)/m...