Tek Eye Logo

Tek Eye

Forms and Dialogs in a Windows DLL with C Sharp

This article covers the programming of Windows forms and dialogs so that they are located in a Windows DLL (dynamic link library). This can help with an apps design, maintenance, and testing, and when adding new features, by breaking up a large project into more manageable chunks. This tutorial assumes you can create and start a WinForms project in Visual Studio, if not see the article Hello World in C#, A Starting WinForms Example

Form from a DLL

Introduction to Windows Forms in a DLL

When it comes to programming an app, try and keep the apps functions contained into small separate units, it'll help with future development and help to avoid spaghetti code. For Windows apps there is the main executable, or .exe, that starts the program. Then, especially for large programs with lots of functionality, there are library files that contain other code the main .exe can use. A library file is .dll file, dll for dynamic link library. Lots of developers add Windows forms (WinForms) to the .exe for the user interface. However, WinForms can be added to dlls to help break up a bigger program into more manageable chunks.

Start with a Test Program and Class Library

For this tutorial a Windows .exe is going to load a WinForm from a DLL. The WinForm is located in a Class Library project, which compiles into a DLL. In Visual Studio create a test app for the .exe, here it is called DLLFormTest, then add a new Class Library project called DLLForm to the new solution (using Add and New Project).

A DLL WinForm Project

Put a WinForm in the DLL and Add References

Next, use the context menu on the .dll project (here called DLLForm) to add a Windows form, using Add then New Item (or add a new form via the Project menu). Rename the form, e.g. to MyForm from Form1, so that you do not get confused with the form in the .exe app, also called Form1. Accept the Visual Studio option to rename all references to the renamed form. Change the new renamed DLL form's text property as well, e.g. from Form1 to MyForm. Delete the Class1 file from the DLLForm project, it won't be used. In the DLLFormTest project add a refernce to the DLLForm Class Library.

Add a WinForm to the DLL

Load the DLL Form from the EXE

Drop a button onto the main EXE's form (in this tutorial Form1 in the DLLFormTest project). Reference the form in the DLL, firstly with using DLLForm, and code to load the DLL form from a button. The code will look similar to this:

using System;
using System.Windows.Forms;
using DLLForm;

namespace DLLFormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            MyForm myForm = new MyForm();
            myForm.Show();
        }
    }
}

Run the code and press the button to load the form from the DLL. When running it will look something like that shown at the beginning of this article. If there are errors check that the form renaming was correct, e.g. the MyForm constructor is correct:

using System.Windows.Forms;

namespace DLLForm
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
        }
    }
}

In the binary output directories for the solution, under the bin folders there will be DLLFormTest.exe and DLLForm.dll, with MyForm in the .dll file.

Showing a DLL WinForm Modally

WinForms can be displayed so that no other form in the app can be used until the new form is closed. The MessageBox is often used by developers to ask the user for a response before carrying on. The enumeration (enum) called DialogResult is returned by a MessageBox. DialogResult is used to test for the MessageBox return value:

private void button2_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Exit app?", "Exiting", MessageBoxButtons.YesNo) == DialogResult.Yes)
        Application.Exit();
}

This type of form is called a Modal form, or sometimes a dialog box. To do the same with a normal WinForm use the ShowDialog() method:

using System;
using System.Windows.Forms;
using DLLForm;

namespace DLLFormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Form myForm = new MyForm();
            myForm.ShowDialog();    //Show modally
        }
    }
}

Returning DialogResult from a WinForm

A normal WinForm that is shown modally can also return DialogResult values. To do it add a button to the form and set the button's DialogResult property.

DialogResult on Button

Try it with the MyForm example. Add two buttons, one with the text Yes and with the DialogResult property set to Yes, and one with the text No and with the DialogResult property set to No. Support for DialogResult allows for fancy custom dialog boxes to be built and stored in a separate dll.

private void button1_Click(object sender, EventArgs e)
{
    MyForm myForm = new MyForm();
    if( myForm.ShowDialog() == DialogResult.Yes )    //Show modally
        Application.Exit();
}

Default Escape and Return Actions

WinForms support default button actions on presses of the return/enter or escape key. For MyForm set the AcceptButton property to the name of the Yes button. For the CancelButton property of MyForm set it to the name of the No button. (Because the DialogResult value for the buttons have been set they override the default values which are DialogResult.OK for a button assigned to the AcceptButton property, and DialogResult.Cancel for a button assigned to the CancelButton property.)

Default Enter Button

DialogResult actions

Setting and Returning Values from a WinForm

For data that is more complex than a DialogResult add extra properties to the DLL form. This allows data to be passed to and from the DLL form. Here a FirstNameField is being used to read and write from a TextBox:

using System.Windows.Forms;

namespace DLLForm
{
    public partial class MyForm : Form
    {
        public MyForm()
        {
            InitializeComponent();
        }

        //Read and update a TextBox for first name
        public string FirstNameField    
        {
            get
            {
                return textBox1.Text;
            }
            set
            {
                textBox1.Text = value;
            }
        }
    }
}

The property is then used to access the forms data fields:

private void button1_Click(object sender, EventArgs e)
{
    MyForm myForm = new MyForm();
    myForm.ShowDialog();
    label1.Text = "The first name is " + myForm.FirstNameField;
}       

An Extra WinForm Property

However, if not using the form modally another event is required to control reading of the data from the form. Here button1 creates the form and button2 reads the data. Notice how the form variable is now at the module level so it can be used by both buttons. There is also extra logic to see if the form is loaded:

using System;
using System.Windows.Forms;
using DLLForm;

namespace DLLFormTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        MyForm myForm;  //Keep a module reference to a form
        private void button1_Click(object sender, EventArgs e)
        {
            //See if we need to create the form
            if (myForm == null || myForm.IsDisposed)
            {
                myForm = new MyForm();
                myForm.Show();
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            //Check for form available
            if (myForm != null && !myForm.IsDisposed)
                label1.Text = "The first name is " + myForm.FirstNameField;
        }
    }
}

Form management can become an issue in large programs, though the Application.OpenForms property and FormCollection class can help. If passing lots of data to and from a form use an object or structure that is common to both forms. Pass a reference to that common object or structure to the form being loaded, then use it to write and read from the forms fields.

See Also

  • For a full list of the articles on Tek Eye see the website's index.

Author:  Published:  

ShareSubmit to TwitterSubmit to FacebookSubmit to Google+Submit to LinkedInSubmit to redditPrint Page

markdown CMS Small Logo Icon ↓markdown↓ CMS is fast and simple. Build websites quickly and publish easily. For beginner to expert.



Articles on:

Android Programming and Android Practice Projects, HTML, VPS, Computing, IT, Computer History, ↓markdown↓ CMS, C# Programming, Using Windows for Programming



Free Android Projects and Samples:

Android Examples, Android List Examples, Android UI Examples



Maintain your PC with Piriform:

CCleaner Professional
CCleaner for Mac
Recuva Professional
Defraggler Professional
Speccy Professional

Shop at Tek Eye for PC utilities