How to make a manually created button invisible after it is clicked in Windows Form?

StackOverflow https://stackoverflow.com/questions/23260587

  •  08-07-2023
  •  | 
  •  

سؤال

I manually created a button using the code below. Usually with buttons I can set their Visible=false to make them invisible, which I do in the setInvisible method I call when the button is clicked. I can't seem to do this with my manually created button, though?

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();
    }
}
هل كانت مفيدة؟

المحلول

You should declare your manual created button as a field, outside the constructor:

private myButtonObject start;

Something like that

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

نصائح أخرى

Please find the code below:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void myButton1_Click(object sender, EventArgs e)
    {
        this.myButton1.Hide();
    }
}

InitilizeComponent method:

        this.myButton1 = new WindowsFormsApplication4.MyButton();
        this.myButton1.Click += new System.EventHandler(this.myButton1_Click);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top