0

For example letting this work:

protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.H)
    {
        this.Close();
        return true;
    }
    else
    {
        return base.ProcessDialogKey(keyData);
    }
}

While I am disabling Alt+f4 from working I can't use e.Cancel = true; because it disables hitting the key H from closing the program.

Chris Ballard
  • 3,771
  • 4
  • 28
  • 40

3 Answers3

2

Try This:

Solution 1:

protected override bool ProcessDialogKey(Keys keyData)
    {
        if (keyData == Keys.H)
        {
            this.Close();
            return true;
        }
        else if (keyData == Keys.Alt | keyData == Keys.F4)
        {
            return base.ProcessDialogKey(keyData);
        }
        return true;
    }

Solution 2:

 private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Alt | e.KeyCode==Keys.F4)
        {
            e.Handled = true;
        }
        else if (e.KeyCode == Keys.H)
        {
            this.Close();
        }
    }
Sudhakar Tillapudi
  • 25,935
  • 5
  • 37
  • 67
1

Try with this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    e.Cancel = (e.CloseReason == CloseReason.UserClosing);
}

This way you cancel the close only when the user is trying to close the form through the user interface.

Check this: How to Disable Alt + F4 closing form?

Community
  • 1
  • 1
thepirat000
  • 12,362
  • 4
  • 46
  • 72
  • @SriramSakthivel You're right. Sudhakar answer is the right one, assuming you will allow the user to close the form with the Close Button. – thepirat000 Mar 14 '14 at 18:47
  • Yes, using close button and also windows context menu too. If user wants to prevent those also this is the way to go:) – Sriram Sakthivel Mar 14 '14 at 19:08
1

What about setting some global variable to close?

bool closeForm = false;
protected override bool ProcessDialogKey(Keys keyData)
{
    if (keyData == Keys.H)
    {
        closeForm = true;
        this.Close();
        return true;
    }
    else
    {
        return base.ProcessDialogKey(keyData);
    }
}

and in your FormClosing event, just check against the variable like so

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (!closeForm)
       e.Cancel = true;
}
boiledham
  • 147
  • 8