Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/320.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 截取CTRL+字母+字母_C# - Fatal编程技术网

C# 截取CTRL+字母+字母

C# 截取CTRL+字母+字母,c#,C#,我想在按下CTRL+A+A的同时拦截 我读了这篇文章 有人在这里贴了一个代码: 不管怎样,我试图修改代码并添加&但是这和其他一些尝试都是错误的 如果我按CTRL+A+A,如何获取 谢谢你的帮助 using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace GlobalHotkeyExampleForm { public partial class Form1 : F

我想在按下CTRL+A+A的同时拦截

我读了这篇文章

有人在这里贴了一个代码:

不管怎样,我试图修改代码并添加&但是这和其他一些尝试都是错误的

如果我按CTRL+A+A,如何获取

谢谢你的帮助

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

namespace GlobalHotkeyExampleForm
{
    public partial class Form1 : Form
    {

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        enum KeyModifier
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            WinKey = 8
        }

        public Form1()
        {
            InitializeComponent();

            int id = 0;     // The id of the hotkey. 
            RegisterHotKey(this.Handle, id, (int)KeyModifier.Control, Keys.A.GetHashCode());       // Register ctrl + a as global hotkey. 
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == 0x0312)
            {
                /* Note that the three lines below are not needed if you only want to register one hotkey.
                 * The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */

                Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);                  // The key of the hotkey that was pressed.
                KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF);       // The modifier of the hotkey that was pressed.
                int id = m.WParam.ToInt32();                                        // The id of the hotkey that was pressed.


                MessageBox.Show("Hotkey has been pressed!");
                // do something
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnregisterHotKey(this.Handle, 0);       // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}

昨天我又回到了这个问题上,最后,我做了我想做的事情,但改变了策略,因为在上面的代码中,我没有真正找到适合我目标的解决方案。我将报告为什么我认为它对其他人有用,也许有人有不同的解决方案

因此,在上面的代码中,我尝试截取CTRL+C+C,然后在Windows剪贴板上获取使用copy的内容。但这里的问题是,代码注册了快捷键,因此任何其他软件都不能继续使用CTRL+C。我试图在缓存按下CTRL+C后取消注册快捷键,但我只发现了问题。无论如何,我不喜欢偷一个快捷键到另一个应用程序,我更喜欢在他们被按下的时候听快捷键

因此,在这里,它跟随一些注释的代码,我将粘贴我发现的解决方案,按下监听键添加一个新的答案

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;

namespace GlobalHotkeyExampleForm
{
    public partial class Form1 : Form
    {

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        public int shortkey = 0;

        [DllImport("user32.dll")]
        private static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vk);
        [DllImport("user32.dll")]
        private static extern bool UnregisterHotKey(IntPtr hWnd, int id);

        enum KeyModifier
        {
            None = 0,
            Alt = 1,
            Control = 2,
            Shift = 4,
            WinKey = 8
        }

        public Form1()
        {
            InitializeComponent();

            int id = 0;     // The id of the hotkey. 
            RegisterHotKey(this.Handle, id, (int)KeyModifier.Control, Keys.C.GetHashCode());       // Register CTRL + C as global hotkey. 
        }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);

            if (m.Msg == 0x0312)
            {
                /* Note that the three lines below are not needed if you only want to register one hotkey.
                 * The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */

                Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);                  // The key of the hotkey that was pressed.
                KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF);       // The modifier of the hotkey that was pressed.
                int id = m.WParam.ToInt32();                                        // The id of the hotkey that was pressed.

                if (modifier == KeyModifier.Control && key == Keys.C)
                {
                    shortkey = shortkey + 1;

                    label1.Text = (shortkey.ToString());

                    //if I enebale this code it works partially. The UnregisterHotKey and RegisterHotKey works perfectly and alone also SendKeys works prefectly, but together it doesn't:
                    //it doesn't recognize that CTRL is still pressed and I don't want to do CTRL C + CTRL C and I don't like "to stole" the shortkey from other apps!;
                    //I tried to use SendKeys to resend CTRL C or onlt CTRL but it doens't work and it creates only Register problems 
                    //UnregisterHotKey(this.Handle, 0); //unregister the hotkey catching
                    //SendKeys.Send("^c"); //send key to active application (it doesn't matter if this is the application)               
                    ////register the hotkey catching as C only
                    //RegisterHotKey(this.Handle, id, (int)KeyModifier.Control, Keys.C.GetHashCode());
                    //SendKeys.Send("^c");
                    //SendKeys.Send("^");
                    timer1.Start();
                }

                //MessageBox.Show("Hotkey has been pressed!");
                // do something
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnregisterHotKey(this.Handle, 0);       // Unregister hotkey with id 0 before closing the form. You might want to call this more than once with different id values if you are planning to register more than one hotkey.
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {

            if (shortkey == 2)
            {
                string returnMyText = Clipboard.GetText(TextDataFormat.Text);
            }
            shortkey = 0;
            timer1.Stop();
        }
    }
}

这是我发现的解决方案,可以倾听关键压力。 我从Dylan的网站上获取了代码,并做了一些更改:

本课程还有几行内容:

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Input;

namespace DesktopWPFAppLowLevelKeyboardHook
{
    public class LowLevelKeyboardListener
    {
        private const int WH_KEYBOARD_LL = 13;
        private const int WM_KEYDOWN = 0x0100;
        private const int WM_KEYUP = 0x101;
        private const int WM_SYSKEYDOWN = 0x104;
        private const int WM_SYSKEYUP = 0x105;

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr SetWindowsHookEx(int idHook, LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool UnhookWindowsHookEx(IntPtr hhk);

        [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode, IntPtr wParam, IntPtr lParam);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        private static extern IntPtr GetModuleHandle(string lpModuleName);

        public delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

        public event EventHandler<KeyPressedArgs> OnKeyPressed;

        private LowLevelKeyboardProc _proc;
        private IntPtr _hookID = IntPtr.Zero;

        public LowLevelKeyboardListener()
        {
            _proc = HookCallback;
        }

        public void HookKeyboard()
        {
            _hookID = SetHook(_proc);
        }

        public void UnHookKeyboard()
        {
            UnhookWindowsHookEx(_hookID);
        }

        private IntPtr SetHook(LowLevelKeyboardProc proc)
        {
            using (Process curProcess = Process.GetCurrentProcess())
            using (ProcessModule curModule = curProcess.MainModule)
            {
                return SetWindowsHookEx(WH_KEYBOARD_LL, proc, GetModuleHandle(curModule.ModuleName), 0);
            }
        }

        private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
        {

            if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                int status = 1;

                if (OnKeyPressed != null) { OnKeyPressed(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode), status)); }
            }
            else if (nCode >= 0 && wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
            {
                int vkCode = Marshal.ReadInt32(lParam);
                int status = 0;

                if (OnKeyPressed != null) { OnKeyPressed(this, new KeyPressedArgs(KeyInterop.KeyFromVirtualKey(vkCode), status)); }
            }

            return CallNextHookEx(_hookID, nCode, wParam, lParam);
        }
    }

    public class KeyPressedArgs : EventArgs
    {
        public Key KeyPressed { get; private set; }
        public int KeyStatus { get; private set; }

        public KeyPressedArgs(Key key, int status)
        {
            KeyPressed = key;
            KeyStatus = status;
        }
    }
}
PS:最初它是WPF应用程序,但我的是WFA,不包括KeyInterop。
因此,我只是在WindowsBase中添加了一个引用程序集。dll

Ctrl+a+a只不过是在一个小时间段内发生的两个Ctrl+a而已。您如何同时按a两次?您希望按键的顺序如何?Ctrl->A->release A->A?或者Ctrl->A->释放A和Ctrl->A?在任何情况下,都不能将Ctrl+A+A注册为单个热键。您必须将Ctrl+A注册为热键,然后检测它是否在某个时间限制内按了两次。@mjwills实际上它并不是同时按两次A,我只是想在按住Ctrl+A后第二次按A,我会说Ctrl仍然是pushed@Herohtar这正是你说的,要检测Ctrl->A->release A->AThis是我文章的第二部分,它应该在下面的文章之后。这是文章的第一部分
using DesktopWPFAppLowLevelKeyboardHook;
using System;
using System.Windows.Forms;

namespace AppLowLevelKeyboardHook
{
    public partial class Form1 : Form
    {
        private LowLevelKeyboardListener _listener;
        public int ctrlStatus;
        public int cStatus;

        public Form1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, EventArgs e)
        {
            _listener = new LowLevelKeyboardListener();
            _listener.OnKeyPressed += _listener_OnKeyPressed;
            _listener.HookKeyboard();
        }

        private void _listener_OnKeyPressed(object sender, KeyPressedArgs e)
        {
            this.textBox_DisplayKeyboardInput.Text += e.KeyPressed.ToString() + e.KeyStatus.ToString();

            if (e.KeyStatus == 1 && (e.KeyPressed.ToString() == "LeftCtrl" || e.KeyStatus.ToString() == "RightCtrl"))
            {
                if (ctrlStatus == 0)
                {
                    ctrlStatus = ctrlStatus + 1;
                    timer1.Start();
                }
            }
            else if (e.KeyStatus == 1 && e.KeyPressed.ToString() == "C")
            {
                if (ctrlStatus == 1 && (cStatus == 0 || cStatus == 2))
                {
                    cStatus = cStatus + 1;
                }
            }
            //no need to wait that CTRL will be released
            //else if (e.KeyStatus == 0 && (e.KeyPressed.ToString() == "LeftCtrl" || e.KeyStatus.ToString() == "RightCtrl"))
            //{
            //    if (ctrlStatus == 1)
            //    {
            //        ctrlStatus = ctrlStatus + 1;
            //    }
            //}
            else if (e.KeyStatus == 0 && e.KeyPressed.ToString() == "C")
            {
                if (ctrlStatus == 1)
                {
                    if (cStatus == 1 || cStatus == 3)
                    {
                        cStatus = cStatus + 1;
                    }
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if ((ctrlStatus == 1) && cStatus == 3 || cStatus == 4) //no need to wait that CTRL will be released (ctrlStatus == 2)
            {
                //do something
                label1.Text = "";
                label1.Refresh();
                label1.Text = Clipboard.GetText(TextDataFormat.UnicodeText);
                //\do something
            }
            ctrlStatus = 0;
            cStatus = 0;
            timer1.Stop();
        }

        private void Window_Closing(object sender, FormClosingEventArgs e)
        {
            _listener.UnHookKeyboard();
        }
    }
}