Trapping Key presses in C# Child form

You can post your problem related to Microsoft Visual Studio Projects here. We will try our best to help you out.
Sean
Posts:22
Joined:Sat Feb 18, 2017 9:02 am
Trapping Key presses in C# Child form

Post by Sean » Tue Mar 07, 2017 8:48 am

I have seen several posts about trapping keys presses but none specific to child forms. In the code fragments below Key presses are trapped when the focus is the parent form but not when the focus is the child form. What else do I need to do to trap those also? I would also like to be able to trap arrow keys in the child form if possible. Unrelated code deleted.

Code: Select all

public partial class Main : Form
    {
        private void btGraph_Click(object sender, EventArgs e)
        {
            Graph WaveGraph = new Graph("Waveform");
            other code placing graphics on the form
        }

        // need to trap arrow keys.
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Up)
            {
                MessageBox.Show("Up key pressed");
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
    }

class Graph
{
    public Graph(string name)
    {
        GraphForm = new Form();
        GraphForm.Name = name;
        GraphForm.KeyPress += new KeyPressEventHandler(OnKeyPress);
        GraphForm.KeyPreview = true;
    }

    // The message box never appears
    private void OnKeyPress(object sender, KeyPressEventArgs e)
    {
        string KeyString = e.KeyChar.ToString();
        MessageBox.Show("A key was pressed");
        return;
    }
}

Post Reply