更新:2007 年 11 月
這個範例示範如何建立一個形狀與標準矩形按鈕不同的按鈕。程式碼會將圓形形狀中的按鈕加入表單,並建立在按一下圓形時會顯示訊息的事件處理常式。
範例
public Form2()
{
//
// Required for Windows Form Designer support.
//
InitializeComponent();
// Initialize the user-defined button,
// including defining handler for Click message,
// location and size.
myButtonObject myButton = new myButtonObject();
EventHandler myHandler = new EventHandler(myButton_Click);
myButton.Click += myHandler;
myButton.Location = new System.Drawing.Point(20, 20);
myButton.Size = new System.Drawing.Size(101, 101);
this.Controls.Add(myButton);
}
public class myButtonObject : UserControl
{
// Draw the new button.
protected override void OnPaint(PaintEventArgs e)
{
Graphics graphics = e.Graphics;
Pen myPen = new Pen(Color.Black);
// Draw the button in the form of a circle
graphics.DrawEllipse(myPen, 0, 0, 100, 100);
myPen.Dispose();
}
}
// Handler for the click message.
void myButton_Click(Object sender, System.EventArgs e)
{
MessageBox.Show("Click");
}
編譯程式碼
此範例需要 Windows Form 應用程式專案,其中包含了名為 Form2 的表單。