[英]How to make a manually created button invisible after it is clicked in Windows Form?
我使用下面的代碼手動創建了一個按鈕。 通常,使用按鈕時,我可以將其Visible=false
設置為不可見,這在單擊按鈕時調用的setInvisible
方法中進行。 我似乎無法使用手動創建的按鈕執行此操作?
myButtonObject start = new myButtonObject();
public MainForm()
{
InitializeComponent();
EventHandler myHandler = new EventHandler(start_Click);
start.Click += myHandler;
start.Location = new System.Drawing.Point(200, 500);
start.Size = new System.Drawing.Size(101, 101);
//start.Text="Start";
this.Controls.Add(start);
}
void start_Click(Object sender, System.EventArgs e)
{
start.Visible=false;
setInvisible(); // sets a group of buttons invisible
setVisible(); // sets another group visible
}
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.FillEllipse(Brushes.Goldenrod, 0, 0, 100, 100);
graphics.DrawEllipse(myPen, 0, 0, 100, 100);
TextRenderer.DrawText(graphics, "Start", new Font("Arial Black", 12.25F, System.Drawing.FontStyle.Bold), new Point(23,37), SystemColors.ControlText);
myPen.Dispose();
}
}
您應該在構造函數之外將手動創建的按鈕聲明為字段 :
private myButtonObject start;
像這樣
public class MainForm()
{
// Declare the button as a field in order to have access to it
// in any property/method/constructor within the class
private myButtonObject start;
...
}
public MainForm()
{
InitializeComponent();
start = new myButtonObject();
EventHandler myHandler = new EventHandler(start_Click);
start.Click += myHandler;
start.Location = new System.Drawing.Point(200, 500);
start.Size = new System.Drawing.Size(101, 101);
this.Controls.Add(start);
...
}
private void setInvisible()
{
...
// You can access the button within setInvisible() method
start.Visible = false;
}
請在下面找到代碼:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void myButton1_Click(object sender, EventArgs e)
{
this.myButton1.Hide();
}
}
InitilizeComponent方法:
this.myButton1 = new WindowsFormsApplication4.MyButton();
this.myButton1.Click += new System.EventHandler(this.myButton1_Click);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.