Instantiate method on instantiated Form

1

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

Form frmDialog = new Form();

Well, I want to do the following, in the form where I instantiated 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 would like to know how to instantiate this method to work in frmDialog (New Form.)

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

    
asked by anonymous 16.03.2018 / 16:18

1 answer

2

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

  

Form.ProcessCmdKey Method (Message, Keys)
link

But it will not 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 that you want. So you could do like this:

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, at the time of using this modified version of class Form , you would have to instantiate your class:

MeuForm frmDialog = new MeuForm();

Although you need to create an object of type MeuForm , you could set the variable to be of type Form , if needed, since MeuForm inherits class Form :

Form frmDialog = new MeuForm();

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

    
16.03.2018 / 16:46