Instantiate method in Instantiated Form

Asked

Viewed 115 times

1

Hello, I am with the following question, I have installed a new form with the following code:

Form frmDialog = new Form();

Well, I want to do the following, in the form in which I instituted this new Form, I can use the following code:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            switch(keyData)
            {
                case Keys.Escape:
                    Close();
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

I wanted to know how to instantiate this method to work in frmDialog (New form.)

What this code does: When I press the Escape key (ESC), the form closes.

  • It needs to be with this method of yours ProcessCmdKey? It cannot be using the KeyDown in frmDialog?

  • It didn’t work, but thanks anyway, I was trying to do with the Keyup and Keypress events, now I know that event.. :)

  • Opa, now yes! Thanks, now I know why I could not use these events in the form.... Thanks really! :)

1 answer

3


Lucas, when you instantiate an object like Form, it will only have the generic methods and properties that are already present in the type Form. In this case, this method is present in the . NET class:

Form.Processcmdkey Method (Message, Keys)
https://msdn.microsoft.com/en-us/library/system.windows.forms.form.processcmdkey.aspx

But, it won’t have that specific functionality you want.

To do what you want, you would have to create a new class that inherits the generic class Form, adding this new functionality you want. Then you could do so:

class MeuForm : Form
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        switch(keyData)
        {
            case Keys.Escape:
                this.Close();
                break;
        }
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

And then, when using this modified version of the class Form, you would have to instantiate the your class:

MeuForm frmDialog = new MeuForm();

Although you need to create an object of the type MeuForm, you could define the variable as being of the type Form, if I had to, since MeuForm inherits the class Form:

Form frmDialog = new MeuForm();

However, if you use this second way, the Intellisense Visual Studio will not show you public properties and methods that are unique to the class MeuForm, only show members specifically exposed by the type Form.

  • Thank you very much! It worked, it really helped me, in the question of doubt and logic! Thank you, have a good day :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.