Johannes Sona Utter
Johannes Sona Utter

Reputation: 23

Playing around with buttons in Windows Forms

I'm on to a small project where I try to make my own web browser.

I found out that a web browser is worthless without "New Tabs"-function, so I thought that I could use buttons as tabs and every time I press "ctrl + T" a new button appears.

The problems I encountered is: -Array of buttons in a way that makes it possible for me to spawn a new button every time I press "ctrl + T"

-When the button is spawned it should be clickable and disabled when clicked until another tab (button) is click.


At the moment I focus on getting 1 tab to work, so here's an example:

    private void TB_Address_KeyPress(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.T && e.Modifiers == Keys.Control)
        {
            Button tabButton = new Button();
            tabButton = new System.Windows.Forms.Button();
            tabButton.BackColor = System.Drawing.SystemColors.ActiveCaptionText;
            tabButton.Cursor = System.Windows.Forms.Cursors.Hand;
            tabButton.ForeColor = System.Drawing.Color.Lime;
            tabButton.Location = new System.Drawing.Point(154, 32);
            tabButton.Name = "tabButton";
            tabButton.Size = new System.Drawing.Size(152, 23);
            tabButton.TabIndex = 13;
            tabButton.Text = "Tab 2";
            tabButton.UseVisualStyleBackColor = false;
            tabButton.Click += new System.EventHandler(this.tabButton_Click);
            Controls.Add(tabButton);
        }
    }

I also have this click function:

    private void tabButton_Click(object sender, EventArgs e)
    {
        tab_1.Enabled = true;
        tabButton.Enabled = false;
    }

"tab_1" is a button created in the design mode. "tabButton.Enabled" is red marked because it cannot find tabButton. I understand why it cannot be found. But I have no idea about how to solve the problem in a good way.

Upvotes: 2

Views: 165

Answers (2)

Johannes Sona Utter
Johannes Sona Utter

Reputation: 23

I'm going with a different method. Creating all the buttons needed initially.

Sorry for wasting your time.

Upvotes: 0

Carlos Landeras
Carlos Landeras

Reputation: 11063

You are assigning the tabButton_Click to all buttons with this line:

 tabButton.Click += new System.EventHandler(this.tabButton_Click);

Just cast the sender to button and you will get the button who fired the event:

void tabButton_Click(object sender, EventArgs e)
{
  Button buttonSender = (Button) sender;
  buttonSender.Enabled=false;
}

You are not finding "tab_1" because it is not a valid name inside the tabButton_Click scope. That's why you have to cast the sender object to WindowsForms Button, and then change its properties.

Upvotes: 4

Related Questions