0

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";
}
Gusdor
  • 14,001
  • 2
  • 52
  • 64
Ram Kumar
  • 23
  • 1
  • 4

4 Answers4

3

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;
    }
Stadub Dima
  • 858
  • 10
  • 24
1

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.

Community
  • 1
  • 1
Yurii
  • 4,811
  • 7
  • 32
  • 41
0

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);
}
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
  • While it's true, [you shouldn't use `KeyPreview` though](http://stackoverflow.com/questions/2386695/disadvantage-of-setting-form-keypreview-true). – CodeCaster Jan 29 '14 at 08:56
-2
// 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);
    }
Saleh Parsa
  • 1,415
  • 13
  • 22
  • 1
    Just dumping some code isn't an answer, and a keyboard hook is a particularly bad way to solve this problem, so -1. – CodeCaster Jan 29 '14 at 08:55