簡體   English   中英

C# - 無法處理 enter 和 tab 鍵事件

[英]C# - unable to process enter and tab key event

我是新的 c#,我正在使用下面的代碼,但該代碼不適用於 Enter 鍵和 Tab 鍵。 請解決這個問題...

private void Panel_Load(object sender, EventArgs e)
{
    this.KeyDown += new KeyEventHandler(C_event);
}

private void C_event(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        Label1.Text = "Enter Key";
        return;
    }
    if (e.keyCode == Keys.Tab)
    {
        Label1.text = "Tab Key";
        return;
    }

    label1.text = "Default";
}

為了能夠處理 Enter/Tab 鍵按下,您應該覆蓋 ProcessCmdKey 方法

 protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (!this.ProcessKey(msg, keyData))
        {
            return base.ProcessCmdKey(ref msg, keyData);
        }
        return false;
    }

    protected virtual bool ProcessKey(Message msg,Keys keyData)
    {
        //The condition needs to be either `if ((keyData & Keys.Enter) == keyData)` or `if (keyData == Keys.Enter)`.
        if ((keyData & Keys.Enter) == Keys.Enter)
        {
            Label1.Text = "Enter Key";
            return true;
        }
        if ((keyData & Keys.Tab) == Keys.Tab)
        {
            Label1.Text = "Tab Key";
            return true;
        }
        return false;
    }

MSDN 文檔對此非常清楚:

某些鍵,例如TABRETURN 、 ESC 和箭頭鍵由控件自動處理。

要讓這些鍵引發 KeyDown 事件,您必須覆蓋IsInputKey上每個控件中的IsInputKey方法。

您需要將Form KeyPreview屬性設置為True

嘗試這個:

private void Panel_Load(object sender, EventArgs e)
{
    this.KeyPreview= true; //add this line
    this.KeyDown += new KeyEventHandler(C_event);
}
// Structure contain information about low-level keyboard input event
    [StructLayout(LayoutKind.Sequential)]
    private struct KBDLLHOOKSTRUCT
    {
        public Keys key;
        public int scanCode;
        public int flags;
        public int time;
        public IntPtr extra;
    }

    //System level functions to be used for hook and unhook keyboard input
    private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int id, LowLevelKeyboardProc callback, IntPtr hMod, uint dwThreadId);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool UnhookWindowsHookEx(IntPtr hook);
    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hook, int nCode, IntPtr wp, IntPtr lp);
    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string name);
    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern short GetAsyncKeyState(Keys key);

    //Declaring Global objects
    private IntPtr ptrHook;
    private LowLevelKeyboardProc objKeyboardProcess;

    private IntPtr CaptureKey(int nCode, IntPtr wp, IntPtr lp)
    {
        if (nCode >= 0)
        {
            KBDLLHOOKSTRUCT objKeyInfo = (KBDLLHOOKSTRUCT)Marshal.PtrToStructure(lp, typeof(KBDLLHOOKSTRUCT));
            if (objKeyInfo.key == Keys.Tab || objKeyInfo.key == Keys.Enter) // Disabling Windows keys
            {
                MessageBox.Show("TAB or Enter  PRESSED");
                return (IntPtr)1;
            }

        }
        return CallNextHookEx(ptrHook, nCode, wp, lp);
    }
    public Form1()
    {
        InitializeComponent();


        //Get Current Module
        ProcessModule objCurrentModule = Process.GetCurrentProcess().MainModule;
        //Assign callback function each time keyboard process
        objKeyboardProcess = new LowLevelKeyboardProc(CaptureKey);
        //Setting Hook of Keyboard Process for current module
        ptrHook = SetWindowsHookEx(13, objKeyboardProcess, GetModuleHandle(objCurrentModule.ModuleName), 0);
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM