Access a button from the form in other class in C# - c#

I want to know if a button is pressed in C# from another class. I have my standard class Form and another class Device. Now I want to access the button from InitializeComponent in Form in my class Device. Does anyone know a good way to do this?
EDIT: If I press on the btnInitialise I want to show a messagebox (with text "test") to start with. I want to use this button in the class Device. I don't rely know how I can reference the button btnInitialise that is automatically made in my form to the class Device.
public class Form1 : System.Windows.Forms.Form
{
#region "Windows Form Designer generated code"
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.btnInitialise = new System.Windows.Forms.Button();
this.cmbdevice = new System.Windows.Forms.ComboBox();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(42, 41);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;
this.tabControl1.Size = new System.Drawing.Size(645, 414);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.grpDevice);
this.tabPage1.Location = new System.Drawing.Point(4, 22);
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
this.tabPage1.Size = new System.Drawing.Size(637, 388);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "tabPage1";
this.tabPage1.UseVisualStyleBackColor = true;
//
// btnInitialise
//
this.btnInitialise.Location = new System.Drawing.Point(351, 16);
this.btnInitialise.Name = "btnInitialise";
this.btnInitialise.Size = new System.Drawing.Size(96, 25);
this.btnInitialise.TabIndex = 21;
this.btnInitialise.Text = "Initialize";
this.btnInitialise.Click += new System.EventHandler(this.btnInitialise_Click);
//
// Form1
//
this.ClientSize = new System.Drawing.Size(1005, 532);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.grpDevice.ResumeLayout(false);
this.grpDevice.PerformLayout();
this.ResumeLayout(false);
}
private TabControl tabControl1;
private TabPage tabPage1;
private Button btnInitialise;
#endregion "Windows Form Designer generated code"
#region "Global variables"
// OpenLayers fields
////Encapsulates a DT-open layers deviceand manages and distributes subsystems for the device
private Device device = null;
#endregion "Global variables"
//Automatically to initialize components of form
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//Set the culture to en-US for decimal point instead of decimal comma in results
CultureInfo english = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = english;
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (device != null)
{
device.Dispose();
}
}
base.Dispose(disposing);
}
/// <summary>
/// The main entry point for the application.
/// </summary>
///
//Run application, show error message if appl doesnt run
[STAThread]
private static void Main()
{
try
{
Application.Run(new Form1());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message.ToString(), "Error");
}
}
}
public class Device
{
//When clicking on the initialize button show messagebox
private void btnInitialise_Click(object sender, EventArgs e)
{
MessageBox.Show("test");
}
}
}

You have to expose the button to other classes. One way to do so would be using public property. e.g.
public Button MyButton
{
get { return button1; }
}
then from the Form class you can use it as
Device d = new Device();
Button b = d.MyButton;
Note: This example is based on what you have asked in the post. However, it is not clear what are you actually going to achieve by getting a button like this! If you add a code sample and more info about the application you are developing we can help you better.

Your Form constructor should look like this:
public Form1()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//Set the culture to en-US for decimal point instead of decimal comma in results
CultureInfo english = new CultureInfo("en-US");
CultureInfo.DefaultThreadCurrentCulture = english;
device = new Device();
this.btnInitialise.Click += new System.EventHandler(device.btnInitialise_Click);
}
Now in Device you should make the eventhandler public, like this:
public class Device
{
//When clicking on the initialize button show messagebox
public void btnInitialise_Click(object sender, EventArgs e)
{
MessageBox.Show("test");
}
}
Now the Device's btnInitialise_Click method will be triggered when you click the button.
Edit: Fixed typo in Device, try Again.

Related

iTunes COM PlayerPositionMS value update interval

I'm working on two C# winforms and WPF applications that utilize the iTunes COM and have noticed some peculiar behavior accessing the PlayerPositionMS property, which is the player's position in milliseconds. The precision of the PlayerPositionMS value is dependent on whether or not the iTunes application has focus or not. The goal for my 2 apps would be to update the player position with the most accuracy. Any assistance would be appreciated.
Below is some sample code to illustrate my point. This is a winforms application with a single label and timer. The timer interval is the default 100 milliseconds, and the tick method updates the label text with the PlayerPositionMS property value. When iTunes has focus the label is updated as expected. But when the winforms application, or anything else, has focus the label is updated roughly every second. The behavior is the same on winforms and WPF.
iTunes version: 12.9.0.167
iTunesLib version: 1.13
Form snip:
Form code:
namespace Test
{
partial class Form_Test
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.label_Position = new System.Windows.Forms.Label();
this.timer_Test = new System.Windows.Forms.Timer(this.components);
this.SuspendLayout();
//
// label_Position
//
this.label_Position.AutoSize = true;
this.label_Position.Location = new System.Drawing.Point(12, 9);
this.label_Position.Name = "label_Position";
this.label_Position.Size = new System.Drawing.Size(16, 13);
this.label_Position.TabIndex = 0;
this.label_Position.Text = "---";
//
// timer_Test
//
this.timer_Test.Enabled = true;
this.timer_Test.Tick += new System.EventHandler(this.UpdateLabel);
//
// Form_Test
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(205, 33);
this.Controls.Add(this.label_Position);
this.Name = "Form_Test";
this.Text = "Test Form";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Label label_Position;
private System.Windows.Forms.Timer timer_Test;
}
}
Code behind:
using iTunesLib;
using System;
using System.Windows.Forms;
namespace Test
{
public partial class Form_Test : Form
{
private static iTunesApp _itunes = new iTunesLib.iTunesApp();
public Form_Test()
{
InitializeComponent();
}
private void UpdateLabel(object sender, EventArgs e)
{
if (_itunes.CurrentTrack != null && _itunes.PlayerState == ITPlayerState.ITPlayerStatePlaying)
label_Position.Text = _itunes.PlayerPositionMS.ToString();
}
}
}
Calling the Resume method before accessing the PlayerPositionMS property seems to work to resolve this:
private void UpdateLabel(object sender, EventArgs e)
{
if (_itunes.CurrentTrack != null && _itunes.PlayerState == ITPlayerState.ITPlayerStatePlaying)
{
_itunes.Resume();
label_Position.Text = _itunes.PlayerPositionMS.ToString();
}
}

Change Label.Text on it's own click event during Runtime?

All I need is a field that can be renamed by users as they wish by just clicking on it, I am using a label as the control here, when ever user click on it user could be able to enter text in the label and when he click outside of the label that enter text would be saved as the label text.
This is a quick solution:
private void label1_Click(object sender, EventArgs e)
{
TextBox tb = null;
if (label1.Controls.Count > 0) // do we already have created our TextBox?
{
tb = ((TextBox)label1.Controls[0]); // yes. set reference.
// is it already visible? we got clicked from outside, so we hide it:
if (tb.Visible) { label1.Text = tb.Text; tb.Hide(); return; };
}
else if (sender == null) return; // clicked from outside: do nothing
else // we need to create the textbox
{
tb = new TextBox();
tb.Parent = label1; // add it to the label's Controls collection
tb.Size = label1.Size; // size it
// set the event that ends editing when focus goes elsewhere:
tb.LostFocus += (ss, ee) => { label1.Text = tb.Text; tb.Hide(); };
}
tb.Text = label1.Text; // get current text
tb.Show(); // display the textbox in place
}
It embeds a TextBox into the Label. Style the Label to be big enough for the expected user entry!
It expects no other controls to be embedded there.
If you need it more than once consider creating a custom editable label from this code!
Note that to work you need to click at a spot where focus can go, not just the empty space around. To remedy that you could code the Click event for the surrounding space, maybe like this:
private void unClickLabel(object sender, EventArgs e) {label1_Click(null, null);}
In the form constructor add this to all the 'outside' controls that won't take focus, like the Form or a TabPage or a PicureBox or a Panel:
public Form1()
{
InitializeComponent();
this.Click += unClickLabel;
tabPage1.Click += unClickLabel;
pictureBox1.Click += unClickLabel;
..
}
Note that the new Label text will not persist program runs! To allow that you need to store it in some outside user settings and load them at startup..
You should create your own UserControl which contains one label and one textbox. Implement its functionality like you want.
I have created a sample usercontrol to give you an idea about it...
Update:
Follow these steps to use this custom control.
Right click on your project and click 'Add-> UserControl'
Name it 'EditableLabelControl' and click Add.
Go to 'EditableLabelControl.Designer.cs' and replace the partial class Code1 below.
Then go to 'EditableLabelControl.cs' and replace second partial class by Code2 below.
Build your solution.
You should be able to add EditableLabelControl to your form(it will be shown in toolbox)
Code1
partial class EditableLabelControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(0, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(35, 13);
this.label1.TabIndex = 0;
this.label1.Text = "label1";
this.label1.MouseClick += new System.Windows.Forms.MouseEventHandler(this.label1_MouseClick);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(0, 0);
this.textBox1.Name = "textBox1";
this.textBox1.TabIndex = 1;
this.textBox1.Visible = false;
this.textBox1.Leave += new System.EventHandler(this.textBox1_Leave);
//
// EditableLabelControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSize = true;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label1);
this.Name = "EditableLabelControl";
this.Size = new System.Drawing.Size(103, 23);
this.ResumeLayout(false);
this.PerformLayout();
}
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox textBox1;
#endregion
}
Code2
public partial class EditableLabelControl : UserControl
{
public EditableLabelControl()
{
InitializeComponent();
}
private void label1_MouseClick(object sender, MouseEventArgs e)
{
textBox1.Visible = true;
textBox1.BringToFront();
textBox1.Focus();
}
private void textBox1_Leave(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
textBox1.Visible = false;
textBox1.SendToBack();
}
}
Just add this EditableLabelControl to your form and it should work.
Try using TextBox instead of Label.
Use a TextBox control and set the ReadOnly property to true, if you would like to have a non-changeable text field. However, keep in mind, the TextBox will not resize automatically and does not support transparency.
You can change the property BackColor to Control and the BorderStyle to none, this will appear like a label.
With more effort you can create a UserControl and switch between the Lable and TextBox.
I recommend using textBox instead.
Replace the label with textBox.
//Set properties. Make the textBox looks like label
yourTextBox.BackColor = SystemColors.Control;
yourTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None;
//Allow user to change text by double clicking it
yourTextBox.DoubleClick += new EventHandler(this.doubleClick);
//Do stuff when user double click it. Double click again to end editing.
public void doubleClick(object sender, EventArgs e)
{
TextBox temp = (TextBox)sender;
temp.ReadOnly = !temp.ReadOnly;
temp.DeselectAll();
if (temp.ReadOnly)
{
//Make the textbox lose focus
this.ActiveControl = null;
}
}

C# auto fit to any screen resolution

I am working on a small project using MS Visual Studio C# 2010.
In my MainFormDesigner.cs file I have the following code. All it does is load a web page from my server. I need the app to fill the display which is 1080 x 1920. But when I save and build the app some the the sizes default to the resolution of the screen I am working on.
Is there a way to automatically size the app to fit the resoltion of any screen the app runs on.
namespace Impa_Browser
{
partial class MainForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.browser = new System.Windows.Forms.WebBrowser();
this.connectLbl = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// browser
//
this.browser.Location = new System.Drawing.Point(0, 0);
this.browser.Margin = new System.Windows.Forms.Padding(0);
this.browser.MinimumSize = new System.Drawing.Size(20, 20);
this.browser.Name = "browser";
this.browser.ScrollBarsEnabled = false;
this.browser.Size = new System.Drawing.Size(1080, 1920); // THIS IS THE RESOLUTION OF THE DISPLAY THE APP WILL RUN ON
this.browser.TabIndex = 0;
this.browser.Url = new System.Uri("example.com", System.UriKind.Absolute);
this.browser.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler(this.browser_DocumentCompleted);
//
// connectLbl
//
this.connectLbl.Dock = System.Windows.Forms.DockStyle.Fill;
this.connectLbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 48F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(204)));
this.connectLbl.Location = new System.Drawing.Point(0, 0);
this.connectLbl.Name = "connectLbl";
this.connectLbl.Size = new System.Drawing.Size(1080, 1092); // THIS KEEPS CHANGING TO THE RESOLUTION OF THE SCREEN I AM WORKING ON
this.connectLbl.TabIndex = 1;
this.connectLbl.Text = " Trying to connect ...[20] Please check your Internet router";
this.connectLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// MainForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1080, 1092); // THIS KEEPS CHANGING TO THE RESOLUTION OF THE SCREEN I AM WORKING ON
this.Controls.Add(this.browser);
this.Controls.Add(this.connectLbl);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Impa";
this.Load += new System.EventHandler(this.MainForm_Load);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.WebBrowser browser;
private System.Windows.Forms.Label connectLbl;
}
}
Many thanks for any help you can provide.
If you are using WinForms you can set the WindowState to FormWindowState Maximized like this.
this.WindowState = FormWindowState.Maximized;
For WPF user WindowsState Maximized
this.WindowState = WindowState.Maximized;
There are a few solutions to achive this goal:
1) Simply change the WindowState property in the Designer to Maximized.
2) If you don't wanna change this property you can do this in code - for example in the Load Event of your form like this:
private void MainForm_Load(object sender, EventArgs e)
{
this.WindowState = FormWindowState.Maximized;
}
3) Overwrite the OnLoad method of your form like this:
protected override OnLoad(EventArgs e)
{
base.OnLoad(e);
this.WindowState = FormWindowState.Maximized;
}
4) If there is a good reason to not work with WindowState you can use the Screenclass object for screen where your form is displayed. For example like this:
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
// get the current screen
Screen screen = Screen.FromControl(this);
// set Location and Size of your form to fit in the WorkingArea
Location = new Point(screen.WorkingArea.Left, screen.WorkingArea.Top);
Size = new Size(screen.WorkingArea.Width, screen.WorkingArea.Height);
}

How to save a Control Array [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I have this code that allow the user to create a button array, any were in a from.
Here and here are two samples of what I am doing (on Create an account now? Click NO and then download the zip file).
The problem or questions is as follow:
I need to save what ever the user makes: for example if he added 5 buttons and saved it, next time when he opens his saved file he will see the 5 button in the same place he save them.
This will allow the user to send the file to another person with the same program and the other person take a look at the created file.
Because of the misunderstanding (comments below) I will post some code with is the second link above. BUT the problem is that I cant find any code to do what I am asking. guys i do not have any idea on how to even start, I mean I know how to save a image from a picture box or some text but the button array is another thing.
Here is the code Simple example code or you can download the second file posted by me and compile it.
ButtomArray.cs
using System;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ManageControls
{
public delegate void SendSelectedButton(object sender);
public class ButtonArray : Hashtable
{
private readonly Form HostForm;
public event SendSelectedButton SelectedButton;
Point buttonLocation;
int cntButton = 0;
public ButtonArray(Form host)
{
HostForm = host;
}
public void AddButton(int left, int top)
{
Button btnElement = new Button();
btnElement.Top = top;
btnElement.Left = left;
btnElement.Tag = cntButton;
btnElement.Cursor = System.Windows.Forms.Cursors.Default;
btnElement.FlatStyle = System.Windows.Forms.FlatStyle.System;
btnElement.Text = "Button " + cntButton.ToString();
btnElement.Click += new EventHandler(btnElement_Click);
btnElement.MouseDown += new MouseEventHandler(btnElement_MouseDown);
btnElement.MouseMove += new MouseEventHandler(btnElement_MouseMove);
this.Add(cntButton.ToString(), btnElement);
HostForm.Controls.Add(btnElement);
btnElement.BringToFront();
cntButton++;
}
public void RemoveButton(string btnIndex)
{
if (this.Count > 0)
{
HostForm.Controls.Remove((Button)this[btnIndex]);
this.Remove(btnIndex);
}
}
private void btnElement_Click(Object sender, System.EventArgs e)
{
if(null != SelectedButton)
SelectedButton(sender);
}
private void btnElement_MouseDown(object sender, MouseEventArgs e)
{
buttonLocation = e.Location;
}
private void btnElement_MouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
((Button)sender).Left += e.X - buttonLocation.X;
((Button)sender).Top += e.Y - buttonLocation.Y;
}
}
}
}
frmMain.cs
using System;
using System.Collections;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ManageControls
{
public partial class frmMain : Form
{
ButtonArray buttonArray;
bool isClicked = false;
Button btnSelected = new Button();
public frmMain()
{
InitializeComponent();
buttonArray = new ButtonArray(this);
this.MouseDown += new MouseEventHandler(frmMain_MouseDown);
buttonArray.SelectedButton += new
SendSelectedButton(buttonArray_SelectedButton);
}
private void buttonArray_SelectedButton(object sender)
{
btnSelected = sender as Button;
}
private void frmMain_MouseDown(object sender, MouseEventArgs e)
{
if (isClicked)
{
buttonArray.AddButton(e.X, e.Y);
this.Cursor = Cursors.Default;
isClicked = false;
}
}
private void tsButton_Click(object sender, EventArgs e)
{
isClicked = true;
this.Cursor = Cursors.Cross;
}
private void tsDelete_Click(object sender, EventArgs e)
{
buttonArray.RemoveButton(btnSelected.Tag.ToString());
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace ManageControls
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmMain());
}
}
}
and the frmMain.Designer.cs
namespace ManageControls
{
partial class frmMain
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tsMain = new System.Windows.Forms.ToolStrip();
this.AddButton = new System.Windows.Forms.ToolStripButton();
this.toolStripButton1 = new System.Windows.Forms.ToolStripSeparator();
this.RemoveButton = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.openLabel1 = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.saveLabel2 = new System.Windows.Forms.ToolStripLabel();
this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
this.tsMain.SuspendLayout();
this.SuspendLayout();
//
// tsMain
//
this.tsMain.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.AddButton,
this.toolStripButton1,
this.RemoveButton,
this.toolStripSeparator1,
this.openLabel1,
this.toolStripSeparator2,
this.saveLabel2,
this.toolStripSeparator3});
this.tsMain.Location = new System.Drawing.Point(0, 0);
this.tsMain.Name = "tsMain";
this.tsMain.RenderMode = System.Windows.Forms.ToolStripRenderMode.System;
this.tsMain.Size = new System.Drawing.Size(740, 25);
this.tsMain.TabIndex = 0;
this.tsMain.Text = "toolStrip1";
//
// AddButton
//
this.AddButton.Image = global::ManageControls.Properties.Resources.Button;
this.AddButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.AddButton.ImageTransparentColor = System.Drawing.Color.Magenta;
this.AddButton.Name = "AddButton";
this.AddButton.Size = new System.Drawing.Size(63, 22);
this.AddButton.Text = "Button";
this.AddButton.Click += new System.EventHandler(this.tsButton_Click);
//
// toolStripButton1
//
this.toolStripButton1.Name = "toolStripButton1";
this.toolStripButton1.Size = new System.Drawing.Size(6, 25);
//
// RemoveButton
//
this.RemoveButton.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
this.RemoveButton.Image = global::ManageControls.Properties.Resources.Delete;
this.RemoveButton.ImageScaling = System.Windows.Forms.ToolStripItemImageScaling.None;
this.RemoveButton.ImageTransparentColor = System.Drawing.Color.White;
this.RemoveButton.Name = "RemoveButton";
this.RemoveButton.Size = new System.Drawing.Size(57, 22);
this.RemoveButton.Text = "Delete";
this.RemoveButton.Click += new System.EventHandler(this.tsDelete_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// openLabel1
//
this.openLabel1.Name = "openLabel1";
this.openLabel1.Size = new System.Drawing.Size(36, 22);
this.openLabel1.Text = "Open";
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// saveLabel2
//
this.saveLabel2.Name = "saveLabel2";
this.saveLabel2.Size = new System.Drawing.Size(31, 22);
this.saveLabel2.Text = "Save";
//
// toolStripSeparator3
//
this.toolStripSeparator3.Name = "toolStripSeparator3";
this.toolStripSeparator3.Size = new System.Drawing.Size(6, 25);
//
// frmMain
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(740, 449);
this.Controls.Add(this.tsMain);
this.Name = "frmMain";
this.Text = "Manage Controls - Sample";
this.tsMain.ResumeLayout(false);
this.tsMain.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip tsMain;
private System.Windows.Forms.ToolStripButton AddButton;
private System.Windows.Forms.ToolStripButton RemoveButton;
private System.Windows.Forms.ToolStripSeparator toolStripButton1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripLabel openLabel1;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripLabel saveLabel2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator3;
}
}
You don't give much information and i'm not going to download your code. But you can create a class which represents the properties that a button can hold such as position / size / text and serialise a collection of this class. Google .NET serialisation and there are hundreds of links on the topic. You can serialise an array and deserialise it easily from a file to dynamically get back all the buttons, then loop through the deserialised collection and add them back to your form.

How can i remove the tabs from tabcontrol using c#

How can i remove the tabs from tabcontrol when i reference each tab to the childform.
I am using a tabcontrol, i want to remove a particular tab from the control. The value i have to do this in a string which i dynamically.
How to remove the tab from tabcontrol using a existing tab name which i have in a string ??
I tried something like...
string tabToRemove = "tabPageName";
for (int i = 0; i < myTabControl.TabPages.Count; i++)
{
if (myTabControl.TabPages[i].Name.Equals(tabToRemove, StringComparison.OrdinalIgnoreCase))
{
myTabControl.TabPages.RemoveAt(i);
break;
}
}
But in the above code, the myTabControl.TabPages.Count is always zero.
Below is the code, to show i am creating the tabs. This is working perfectly.
public void TabIt(string strProcessName)
{
this.Show();
//Creating MDI child form and initialize its fields
MDIChild childForm = new MDIChild();
childForm.Text = strProcessName;
childForm.MdiParent = this;
//child Form will now hold a reference value to the tab control
childForm.TabCtrl = tabControl1;
//Add a Tabpage and enables it
TabPage tp = new TabPage();
tp.Parent = tabControl1;
tp.Text = childForm.Text;
tp.Show();
//child Form will now hold a reference value to a tabpage
childForm.TabPag = tp;
//Activate the MDI child form
childForm.Show();
childCount++;
//Activate the newly created Tabpage.
tabControl1.SelectedTab = tp;
tabControl1.ItemSize = new Size(200, 32);
tp.Height = tp.Parent.Height;
tp.Width = tp.Parent.Width;
}
public void GetTabNames()
{
foreach (string strProcessName in Global.TabProcessNames)
{
TabIt(strProcessName);
}
}
The child form :
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Drawing.Drawing2D;
namespace Daemon
{
/// <summary>
/// Summary description for MDIChild.
/// </summary>
///
public class MDIChild : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.Container components = null;
private TabControl tabCtrl;
private TabPage tabPag;
public MDIChild()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//MDIChild TargerForm = new MDIChild();
//WinApi.SetWinFullScreen(TargerForm.Handle);
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if(components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
public TabPage TabPag
{
get
{
return tabPag;
}
set
{
tabPag = value;
}
}
public TabControl TabCtrl
{
set
{
tabCtrl = value;
}
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// MDIChild
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.SystemColors.InactiveCaptionText;
this.ClientSize = new System.Drawing.Size(0, 0);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "MDIChild";
this.Opacity = 0;
this.ShowIcon = false;
this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
this.Text = "MDIChild";
this.Activated += new System.EventHandler(this.MDIChild_Activated);
this.Closing += new System.ComponentModel.CancelEventHandler(this.MDIChild_Closing);
this.ResumeLayout(false);
}
#endregion
private void MDIChild_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
try
{
//Destroy the corresponding Tabpage when closing MDI child form
this.tabPag.Dispose();
//If no Tabpage left
if (!tabCtrl.HasChildren)
{
tabCtrl.Visible = false;
}
}
catch (Exception ex)
{
}
}
private void MDIChild_Activated(object sender, System.EventArgs e)
{
try
{
//Activate the corresponding Tabpage
tabCtrl.SelectedTab = tabPag;
if (!tabCtrl.Visible)
{
tabCtrl.Visible = true;
}
Global.ExistingTabProcessNames.Add(tabPag.Text);
}
catch (Exception ex)
{
}
}
}
}
For starters you should be looping the other way around:
for (int i = myTabControl.TabPages.Count - 1; i >= 0 ; i--)
{
......
}
EDIT: Ignore me. I missed the break; and yes it should also be >= :(
My next theory is you are missing this line:
// add the page to the tab control
tabControl1.Controls.Add(tp);
PS: Why does copying code from SO not maintain the CRLFs. That is very annoying!
As jussij suggested, you need to do this:
tabControl1.Controls.Add(tp);
And you can more easily locate the tab like this:
var foundTab = (from System.Windows.Forms.TabPage tab in tabControl1.TabPages.Cast<TabPage>()
where tab.Name == "tabName"
select tab).First();
I dont know the purpose of your code, but if you will eventually re-add the tab, why not just hide it? Its easier and you dont have to worry about reverse loop logic and invalid arguments once the page is hidden and such. If you need to need a way to address all the tabs at once just do a check for visible tabs...
I would recommend taking a look at this tab page example for adding/removing tabs.

Categories

Resources