C# Windows Forms UserControl Examples

Let us look at a simple C# Windows Forms UserControl example.

Example 1: UserControl

This example will comprise the following files:

  • UserControl.cs

Step 1: Create Project

  1. The first step is to create a C# Project.
  2. Go to FILE-->New-->Project to create a new project.

Step 2: Write Code

Write Code as follows:

*(a). UserControl.cs

Create a file named UserControl.cs

Here is the full code

using System;
using System.Windows.Forms;

namespace Examples {
  class MainForm : Form {
    public static void Main() {
      Application.EnableVisualStyles();
      Application.Run(new MainForm());
    }

    public MainForm() {
      Text = "UserControl example";

      userControl1.Parent = this;
      userControl1.BackColor = System.Drawing.Color.LightBlue;
      userControl1.Cursor = Cursors.Hand;
      userControl1.Location = new System.Drawing.Point(50, 50);
      userControl1.DoubleClick += delegate {
        userControl1.BackColor = userControl1.BackColor == System.Drawing.Color.LightBlue ? System.Drawing.Color.LightPink : System.Drawing.Color.LightBlue;
      };
    }

    private UserControl userControl1 = new UserControl();
  }
}

Run

Simply copy the source code into your C# Project,Build and Run. Alternatively download the code using the links provided below, then open the .csproj project, build and run.

Reference

Download the code using the below links:

Number Link
1. Download Example
2. Follow code author

Related Posts