Udostępnij za pośrednictwem


How to: Display Forms from Components

Although most components do not have visual interfaces, there are times when it may be useful for a user to interact visually with a component. For example, a component that represents a bank account might display a specialized alert form when the account is overdrawn. These functions should remain constant in the component and not depend on the client application. Because forms are classes, it is easy to create an instance of the form, and then display it through your component.

There are two approaches you can use to create a form:

  • Create the form outside your component, which enables you to use a design environment like Visual Studio to create the appearance and behavior (look and feel) of the form.

  • Make the form a nested class within your component. An advantage to this approach is that the form is always a part of your component, and you have control over how it is used and exposed. The chief disadvantage, however, is that you will be unable to use a designer with your form, and will have to design it all by manual coding.

To display a form from your component

  1. Create the Windows Form you want to display from your component.

    If the form you want to display is not in the same assembly as your component, you must reference the assembly that contains your form to build correctly.

  2. Declare a local variable as a new instance of the form.

    For example, if your form was called MyForm, your code would look like the following.

    Dim AFormInstance as New MyForm
    
    MyForm AFormInstance = new MyForm();
    
    MyForm AFormInstance =  new MyForm();
    
  3. Call the Show, ShowDialog, and Hide methods of your form to control display, as is shown in the following code examples.

    AFormInstance.Show 
    ' Displays the form.
    AFormInstance.ShowDialog 
    ' Displays the form and waits for user interaction before continuing.
    AFormInstance.Hide 
    ' Hides the form.
    
    // Displays the form.
    AFormInstance.Show();
    // Displays the form and waits for user interaction before continuing.
    AFormInstance.ShowDialog();
    // Hides the form.
    AFormInstance.Hide();
    
    // Displays the form.
    AFormInstance.Show();
    // Displays the form and waits for user interaction before continuing.
    AFormInstance.ShowDialog();
    // Hides the form.
    AFormInstance.Hide();
    

See Also

Other Resources

Component Authoring