在很多的情况下我们需要自己来编写一些控件,下边我就以按扭控件为示例,来介绍一下如何编写控件。首先我们建立一个WindowsApplication类型的工程,然后再新键一个WindowsControlLibrary类型的工程,最好选择Add to Solution,这样的话方便调试。下边我们首先在控件上画一个按扭。还要把它的click事件放映到 它的父容器(form1)中。这里我是在控件中自定义一个事件,当控件中触发了这个事件时,父容器中有一个处理函数做响应。具体操作请看下边的代码,这是控件上的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Drawing2D;
namespace WindowsControlLibrary1
{
public partial class UserControl1 : UserControl
{
public event EventHandler PlayGame;//定义一个事件自己定义的事件
bool flag = true;
public UserControl1()
{
InitializeComponent();
}
private void UserControl1_Paint(object sender, PaintEventArgs e)
{
Color bottomcolor = Color.FromArgb(178, 176, 163);
Color topcolor = Color.FromArgb(252, 251, 249);
int starx = 0;
int stary = 0;
int width = this.Width;
int height = this.Height;
if (flag)
{
Rectangle r = new Rectangle(starx, stary, width, height);
LinearGradientBrush lb = new LinearGradientBrush(r, topcolor, bottomcolor,
LinearGradientMode.Vertical);
e.Graphics.FillRectangle(lb, r);
Pen pen = new Pen(Color.Black, 2);
e.Graphics.DrawRectangle(pen, 0, 0, this.Width, this.Height);
}
else
{
Rectangle r = new Rectangle(starx, stary, width, height);
LinearGradientBrush lb = new LinearGradientBrush(r,bottomcolor,topcolor,
LinearGradientMode.Vertical);
e.Graphics.FillRectangle(lb, r);
Pen pen = new Pen(Color.Black, 1);
e.Graphics.DrawRectangle(pen, 0, 0, this.Width, this.Height);
}
}
private void UserControl1_Load(object sender, EventArgs e)
{
}
private void UserControl1_MouseClick(object sender, MouseEventArgs e)
{
if (flag == true)
{
flag = false;
this.Invalidate();//这是为了点击按扭时来重新画按扭
}
else
{
flag = true;
this.Invalidate();
}
}
this.PlayGame(this, e);//在这里触发事件
}
}
下边是 Form 窗口的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WindowsControlLibrary1;
namespace WindowsApplication4
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.userControl11.PlayGame += new EventHandler(UserControl1_MouseClick);//定义响应事件的函数
}
private void userControl11_Load(object sender, EventArgs e)
{
}
private void UserControl1_MouseClick(object sender, System.EventArgs e)
{
MessageBox.Show("点击事件");//对控件的click事件作出放映
}
private void userControl11_Load_1(object sender, EventArgs e)
{
}
}
}


浙公网安备 33010602011771号