RobertSF
RobertSF

Reputation: 528

How to prevent keystroke in child form reaching parent form?

I have a form that, upon user request, opens a child form, like so --

private void toolTrim_Click(object sender, EventArgs e)
{
    Form form = new TrimOptions();
    form.ShowDialog();
    if (form.DialogResult == DialogResult.OK)
    {
      //code;
    }
{

This child form has a button called btnOk and its property AcceptButton set to btnOk. This means that, when the Enter key is pressed in the child form, it's as if you had clicked on the Ok button, and this code executes.

private void btnOk_Click(object sender, EventArgs e)
{
    Properties.Settings.Default.Save();
    DialogResult = DialogResult.OK;
    Close();
}

The problem is that, when the child form closes, the Enter key that was used to close the child form is captured by the DataGridView in the parent form.

    private void filesDataGridView_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Return) //execution stops here if breakpointed

There's a legitimate use for that, but only when the DGV has focus, not when some child form of this form has focus.

So, how to prevent keystrokes in a child form from "bubbling up" to a parent form?

Upvotes: 0

Views: 526

Answers (2)

RobertSF
RobertSF

Reputation: 528

Following Steve's advice, I removed the Close(); having learned that setting DialogResult to any value other than None will close the window.

Following Hans Passant's advice to use KeyDown instead of KeyUp, I realized I had a mixture of KeyDowns and KeyUps. He was also correct, of course, that indeed the DGV had focus. I made them all KeyDowns, and my problem went away.

Upvotes: 1

coder_b
coder_b

Reputation: 1025

the other solution would be before opening modal you can disable the parent form once dialog is closed you can enable the parent form, so key up event does not fire.

Upvotes: 0

Related Questions