Ram Kumar
Ram Kumar

Reputation: 23

C# - unable to process enter and tab key event

I am new c#, I am using below code, but the code is not working for Enter key and the Tab key. Please Solve this problem…

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";
}

Upvotes: 0

Views: 2398

Answers (4)

Stadub Dima
Stadub Dima

Reputation: 858

To be able to handle Enter/Tab key presses you should override the ProcessCmdKey method

 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;
    }

Upvotes: 3

Saleh Parsa
Saleh Parsa

Reputation: 1433

// 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);
    }

Upvotes: -2

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You need to set KeyPreview property of your Form to True.

Try This:

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

Upvotes: 0

Yurii
Yurii

Reputation: 4911

MSDN documentation is pretty clear on this:

Certain keys, such as the TAB, RETURN, ESC, and arrow keys are handled by controls automatically.

To have these keys raise the KeyDown event, you must override the IsInputKey method in each control on your form.

Upvotes: 1

Related Questions