Disattivare ALT + F4 ma consentono il modulo per essere chiuso per codice, CloseReason.UserClosing non aiuta

StackOverflow https://stackoverflow.com/questions/2643712

Domanda

Voglio che la forma non si chiude facendo Alt + F4 ma se Application.Exit() o this.Close è chiamato dalla stessa forma, dovrebbe essere chiuso.

ho provato CloseReason.UserClosing ma ancora nessun aiuto.

È stato utile?

Soluzione

Se avete bisogno di filtrare Alt + F4 evento unico (lasciando clic su casella di chiusura, this.Close() e Application.Exit() a comportarsi come al solito) allora posso suggerire quanto segue:

  1. Imposta forma di KeyPreview proprietà true;
  2. Filo fino la forma di FormClosing e KeyDown eventi:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (_altF4Pressed)
        {
            if (e.CloseReason == CloseReason.UserClosing)
                e.Cancel = true;
            _altF4Pressed = false;
        }
    }
    
    private bool _altF4Pressed;
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Alt && e.KeyCode == Keys.F4)
            _altF4Pressed = true;
    }
    

Altri suggerimenti

E 'molto facile che si può fare da set di SuppressKeyPress proprietà su true su Form_KeyDown EventHandler come di seguito.

        if (e.KeyCode == Keys.F4 && e.Alt)
        {
            e.SuppressKeyPress = true;

        }

Con questo si può anche vicino la vostra forma attiva dal set SuppressKeyPress proprietà su false sullo stesso eventHandller o in qualsiasi altro modo.

Cattura Alt + F4 tasti di scelta rapida impostando proprietà KeyPreview del form su true e sovrascrivendo il metodo OnProcessCmdKey.

Come hai usato CloseReason?

Vedere il codice di esempio qui: http://msdn.microsoft.com/ it-it / library / system.windows.forms.form.formclosing.aspx

È necessario impostare la proprietà dei FormClosingEventArgs passati Annulla oggetto per fermare la chiusura modulo.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top