winform 热键 kill指定进程

原创 2017年06月02日 12:03:29
引用:
Microsoft.CSharp
System
System.Core
System.Data
System.Data.DataSetExtensions
System.deployment
System.Drawing
System.Management
System.Windows.Forms
System.Xml
System.Xml.Linqusing System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace Copy
{
    public class Win32Api
    {
        #region 常数和结构
        public const int WM_KEYDOWN = 0x100;
        public const int WM_KEYUP = 0x101;
        public const int WM_SYSKEYDOWN = 0x104;
        public const int WM_SYSKEYUP = 0x105;
        public const int WH_KEYBOARD_LL = 13;


        [StructLayout(LayoutKind.Sequential)] //声明键盘钩子的封送结构类型 
        public class KeyboardHookStruct
        {
            public int vkCode; //表示一个在1到254间的虚似键盘码 
            public int scanCode; //表示硬件扫描码 
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
        #endregion


        #region Api
        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        //安装钩子的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        //卸下钩子的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        //下一个钩挂的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
        [DllImport("user32")]
        public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
        [DllImport("user32")]
        public static extern int GetKeyboardState(byte[] pbKeyState);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr GetModuleHandle(string lpModuleName);
        #endregion
    }
}




Form1:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Copy
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        KeyboardHook kh;
        private void Form1_Load(object sender, EventArgs e)
        {
            kh = new KeyboardHook();
            kh.SetHook();
            kh.OnKeyDownEvent += kh_OnKeyDownEvent;
        }


        public void mainCopyXML()
        {
            string XMLPath = this.txt_xml.Text;
            string VPath = this.txt_path.Text;
            string copycmd = "xcopy  " + XMLPath + " " + VPath + "/y";
            functioncmd(copycmd);
        } 
        
        public void mainCopyXMLDLL()
        {
            string systemUsername = "";
            int pid = 0;
            Process[] myProcess = Process.GetProcesses();
            foreach (Process p in myProcess)
            {
                if (p.ProcessName == "w3wp")
                {
                    pid = p.Id;
                    SelectQuery query1 = new SelectQuery("Select * from Win32_Process WHERE processID=" + pid);
                    ManagementObjectSearcher searcher1 = new ManagementObjectSearcher(query1);
                    foreach (ManagementObject disk in searcher1.Get())
                    {
                        ManagementBaseObject inPar = null;
                        ManagementBaseObject outPar = null;
                        inPar = disk.GetMethodParameters("GetOwner");
                        outPar = disk.InvokeMethod("GetOwner", inPar, null);
                        systemUsername = outPar["User"].ToString();
                    }
                    if (systemUsername == "ASP.NET v4.0 Classic")
                    {
                        // MessageBox.Show("come in here" + "   " + systemUsername + "  pid: " + pid);
                        p.Kill();
                    }
                }
            }
            string XMLPath = this.txt_xml.Text;
            string DLLPath = this.txt_dll.Text;
            string VPath = this.txt_path.Text;
            string copycmd = "xcopy  " + DLLPath + " " + VPath + "/y";
            functioncmd(copycmd);
        }


        /// <summary>
        ///-**-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* 程序住入口*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void kh_OnKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.KeyData == (Keys.E | Keys.Control))
            {
                Task t2 = Task.Factory.StartNew(mainCopyXML);
            }
            if (e.KeyData == (Keys.Q | Keys.Control))
            {
                Task t3 = Task.Factory.StartNew(mainCopyXMLDLL);
            }
        }
        public static void functioncmd(string bb)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            p.StandardInput.WriteLine(bb + "&exit");
            p.StandardInput.AutoFlush = true;
            //MessageBox.Show("操作成功!", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            kh.UnHook();
        }
        private void but_xml_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\Documents and Settings\Administrator.ICBCOA-6E96E6BE\桌面";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txt_xml.Text = ofd.FileName;
            }
        }
        private void but_dll_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\Documents and Settings\Administrator.ICBCOA-6E96E6BE\桌面";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txt_dll.Text = ofd.FileName;
            }
        }
        private void but_path_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.InitialDirectory = @"C:\inetpub\wwwroot\HRLINK\WebFrame\pagegenerate";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                txt_path.Text = ofd.FileName.Substring(0, ofd.FileName.LastIndexOf(@"\"));
            }
        }
    }
}








KeyboardHook:




using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace Copy
{
    public class KeyboardHook
    {
        int hHook;
        Win32Api.HookProc KeyboardHookDelegate;
        public event KeyEventHandler OnKeyDownEvent;
        public event KeyEventHandler OnKeyUpEvent;
        public event KeyPressEventHandler OnKeyPressEvent;
        public KeyboardHook() { }
        public void SetHook()
        {
            KeyboardHookDelegate = new Win32Api.HookProc(KeyboardHookProc);
            Process cProcess = Process.GetCurrentProcess();
            ProcessModule cModule = cProcess.MainModule;
            var mh = Win32Api.GetModuleHandle(cModule.ModuleName);
            hHook = Win32Api.SetWindowsHookEx(Win32Api.WH_KEYBOARD_LL, KeyboardHookDelegate, mh, 0);
        }
        public void UnHook()
        {
            Win32Api.UnhookWindowsHookEx(hHook);
        }
        private List<Keys> preKeysList = new List<Keys>();//存放被按下的控制键,用来生成具体的键
        private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam)
        {
            //如果该消息被丢弃(nCode<0)或者没有事件绑定处理程序则不会触发事件
            if ((nCode >= 0) && (OnKeyDownEvent != null || OnKeyUpEvent != null || OnKeyPressEvent != null))
            {
                Win32Api.KeyboardHookStruct KeyDataFromHook = (Win32Api.KeyboardHookStruct)Marshal.PtrToStructure(lParam, typeof(Win32Api.KeyboardHookStruct));
                Keys keyData = (Keys)KeyDataFromHook.vkCode;
                //按下控制键
                if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == Win32Api.WM_KEYDOWN || wParam == Win32Api.WM_SYSKEYDOWN))
                {
                    if (IsCtrlAltShiftKeys(keyData) && preKeysList.IndexOf(keyData) == -1)
                    {
                        preKeysList.Add(keyData);
                    }
                }
                //WM_KEYDOWN和WM_SYSKEYDOWN消息,将会引发OnKeyDownEvent事件
                if (OnKeyDownEvent != null && (wParam == Win32Api.WM_KEYDOWN || wParam == Win32Api.WM_SYSKEYDOWN))
                {
                    KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData));


                    OnKeyDownEvent(this, e);
                }
                //WM_KEYDOWN消息将引发OnKeyPressEvent 
                if (OnKeyPressEvent != null && wParam == Win32Api.WM_KEYDOWN)
                {
                    byte[] keyState = new byte[256];
                    Win32Api.GetKeyboardState(keyState);
                    byte[] inBuffer = new byte[2];
                    if (Win32Api.ToAscii(KeyDataFromHook.vkCode, KeyDataFromHook.scanCode, keyState, inBuffer, KeyDataFromHook.flags) == 1)
                    {
                        KeyPressEventArgs e = new KeyPressEventArgs((char)inBuffer[0]);
                        OnKeyPressEvent(this, e);
                    }
                }
                //松开控制键
                if ((OnKeyDownEvent != null || OnKeyPressEvent != null) && (wParam == Win32Api.WM_KEYUP || wParam == Win32Api.WM_SYSKEYUP))
                {
                    if (IsCtrlAltShiftKeys(keyData))
                    {
                        for (int i = preKeysList.Count - 1; i >= 0; i--)
                        {
                            if (preKeysList[i] == keyData) { preKeysList.RemoveAt(i); }
                        }
                    }
                }
                //WM_KEYUP和WM_SYSKEYUP消息,将引发OnKeyUpEvent事件 
                if (OnKeyUpEvent != null && (wParam == Win32Api.WM_KEYUP || wParam == Win32Api.WM_SYSKEYUP))
                {
                    KeyEventArgs e = new KeyEventArgs(GetDownKeys(keyData));
                    OnKeyUpEvent(this, e);
                }
            }
            return Win32Api.CallNextHookEx(hHook, nCode, wParam, lParam);
        }
        //根据已经按下的控制键生成key
        private Keys GetDownKeys(Keys key)
        {
            Keys rtnKey = Keys.None;
            foreach (Keys i in preKeysList)
            {
                if (i == Keys.LControlKey || i == Keys.RControlKey) { rtnKey = rtnKey | Keys.Control; }
                if (i == Keys.LMenu || i == Keys.RMenu) { rtnKey = rtnKey | Keys.Alt; }
                if (i == Keys.LShiftKey || i == Keys.RShiftKey) { rtnKey = rtnKey | Keys.Shift; }
            }
            return rtnKey | key;
        }
        private Boolean IsCtrlAltShiftKeys(Keys key)
        {
            if (key == Keys.LControlKey || key == Keys.RControlKey || key == Keys.LMenu || key == Keys.RMenu || key == Keys.LShiftKey || key == Keys.RShiftKey) { return true; }
            return false;
        }
    }
}








Win32Api:




using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


namespace Copy
{
    public class Win32Api
    {
        #region 常数和结构
        public const int WM_KEYDOWN = 0x100;
        public const int WM_KEYUP = 0x101;
        public const int WM_SYSKEYDOWN = 0x104;
        public const int WM_SYSKEYUP = 0x105;
        public const int WH_KEYBOARD_LL = 13;


        [StructLayout(LayoutKind.Sequential)] //声明键盘钩子的封送结构类型 
        public class KeyboardHookStruct
        {
            public int vkCode; //表示一个在1到254间的虚似键盘码 
            public int scanCode; //表示硬件扫描码 
            public int flags;
            public int time;
            public int dwExtraInfo;
        }
        #endregion


        #region Api
        public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam);
        //安装钩子的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
        //卸下钩子的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern bool UnhookWindowsHookEx(int idHook);
        //下一个钩挂的函数 
        [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern int CallNextHookEx(int idHook, int nCode, Int32 wParam, IntPtr lParam);
        [DllImport("user32")]
        public static extern int ToAscii(int uVirtKey, int uScanCode, byte[] lpbKeyState, byte[] lpwTransKey, int fuState);
        [DllImport("user32")]
        public static extern int GetKeyboardState(byte[] pbKeyState);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
        public static extern IntPtr GetModuleHandle(string lpModuleName);
        #endregion
    }
}


版权声明:本文为博主原创文章,未经博主允许不得转载。

kill 指定用户所有进程

kill -9 `ps -ef|grep testbaby|grep -v grep|cut -c9-14` //python 提取url import re import urllib ...
  • wind0513
  • wind0513
  • 2010年07月18日 17:00
  • 889

Redhat Linux kill指定进程名的四种方式

1、#pkill 进程名  2、#killall 进程名 3、#kill -9 $(ps -ef|grep 进程名关键字|grep -v grep|awk '{print $2}')这个是利用管道...
  • wjx515628
  • wjx515628
  • 2014年07月16日 13:22
  • 2850

kill某个应用程序进程的方法

结合网上搜索的资料得到两种方法: 1.kill $(pgrep /app/loadingWidget) 2.kill $(ps -ef | grep /app/loadingWidget | grep...
  • aristolto
  • aristolto
  • 2017年05月26日 14:10
  • 615

shell 杀死指定进程名称的进程方法

ps -efww|grep -w 'helloworld'|grep -v grep|cut -c 9-15|xargs kill -9 说明:管道符“|”用来隔开两个命令,管道符左边命令的...
  • Primeprime
  • Primeprime
  • 2016年09月02日 16:58
  • 6635

WinForm 如何注册热键?

 Q:WinForm 如何注册热键?A:using   System; using   System.Collections.Generic; using   System.ComponentMode...
  • jinjazz
  • jinjazz
  • 2007年11月15日 00:57
  • 2405

java通过进程名杀掉指定的linux进程

这几天公司给了个任务,大体是找出进程并kill掉。  带我的师傅给了个语句:Process pid=Runtime.getRuntime().exec("ps -ef | grep 进程名 |gre...
  • lanwuchun
  • lanwuchun
  • 2014年12月06日 11:42
  • 1491

linux杀死指定进程的命令

1)根据pid文件杀死进程             命令:cat test.pid | xargs kill -9             注意事项:如果是在windows上编写的shell 脚本...
  • azhao_dn
  • azhao_dn
  • 2013年06月18日 23:06
  • 4125

Linux下通过端口Kill掉进程

这个操作主要由四步组成: 1 netstat -nlp 查看占用端口号的服务 2 找到该端口号的进程 3 找到该进程id 4 kill 我们一个一个分析: 1 查看占用端口号的服务 我们...
  • houyaowei
  • houyaowei
  • 2016年05月18日 14:43
  • 627

Linux上根据进程名kill掉指定的进程

Linux上根据进程名kill掉指定的进程 def kill_by_name(name): p = subprocess.Popen(['ps', '-A'], stdout=subpr...
  • dongtianlaile
  • dongtianlaile
  • 2016年02月16日 14:19
  • 1118

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

1、窗体热键 首先要设置主窗体KeyPreview为true,可直接在属性中进行设置, 或者在窗体加载中设置: this.KeyPreview = true; 然后添加窗体KeyDown事件,如...
  • cuoban
  • cuoban
  • 2016年02月26日 16:16
  • 3649
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:winform 热键 kill指定进程
举报原因:
原因补充:

(最多只允许输入30个字)