在Windows窗体中单击后,如何使手动创建的按钮不可见?

时间:2014-04-24 05:35:06

标签: c# button invisible

我使用下面的代码手动创建了一个按钮。通常使用按钮我可以设置他们的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();
    }
}

2 个答案:

答案 0 :(得分:2)

您应该在构造函数之外将您的手动创建按钮声明为字段

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;
}

答案 1 :(得分:0)

请找到以下代码:

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);