How To Make The Main Form Capture Keyboard Input - WinForms

 If you would like to capture all key presses on your main form take these steps:

1) Set KeyPreview to True

2) Add an event handler for KeyPress

3) Use the method like so:

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    MyTextRect item = GetTheOneBeingEdited();

    if (item == null) return; 

    panelMainWorkArea.Focus();

    if (!char.IsControl(e.KeyChar))
    { // anything that's not a control character
        item.Text += e.KeyChar;
    }

    else if (e.KeyChar == '\b')
    { // backspace
        item.Text = item.Text.Substring(0, item.Text.Length - 1);
    }

    else if (e.KeyChar == 22)
    { // ctrl + v
        item.Text += Clipboard.GetText();
    }

    else if (e.KeyChar == '\r')
    { // enter
        item.Text += Environment.NewLine;
    }

    panelMainWorkArea.Invalidate();
} 

4) If you want to capture other keys like the arrow keys,  you will need to override ProcessCmdKey:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    try
    {
        if (keyData == Keys.Up)
        {
            // do something with UP arrow
            return true;
        }
        else if (keyData == Keys.Right)
        {
            // do something with RIGHT arrow
            return true;
        }
        else if (keyData == Keys.Down)
        {
            // do something with DOWN arrow
            return true;
        }
        else if (keyData == Keys.Left)
        {
            // do something with Left arrow
            return true;
        }
    }
    catch { }
    return base.ProcessCmdKey(ref msg, keyData);
}


Comments