ToolStripPanel Join method isn't adding toolstrip to panel - c#

I've got a really weird problem with ToolStripPanel.Join and I've been searching on Google and SO for some clue as to what I'm doing wrong but I can't figure it out. Basically, when I use ToolStripPanel.Join, the first ToolStrip that I add doesn't appear at all in the ToolStripPanel but all other ToolStrips that I join will appear. Before I get too far into the details, let me first say that I'm using C# and VS 2010 and .NET 4 and, just for some context, I'm trying to use a ToolStripPanel on a user control which is inside of a custom dll that we made so that we could reuse these user controls in other forms.
I was previously using a ToolStripContainer but I decided to switch out to use a ToolStripPanel since we only really needed the top panel of the ToolStripContainer; I didn't see the point of using a ToolStripContainer. Since I couldn't find a ToolStripPanel control in the Toolbox, I decided to add it myself in the Designer.cs file. Here's how I did it:
private ToolStripPanel tsPanel;
<--Other code here-->
private void InitializeComponent()
{
this.tsPanel = new System.Windows.Forms.ToolStripPanel();
<--Other code here-->
//
// tsPanel
//
this.tsPanel.Dock = System.Windows.Forms.DockStyle.Top;
this.tsPanel.Location = new System.Drawing.Point(0, 0);
this.tsPanel.Margin = new System.Windows.Forms.Padding(3);
this.tsPanel.Name = "tsPanel";
this.tsPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.tsPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.tsPanel.Size = new System.Drawing.Size(1000, 0);
<--Other code here-->
//
// MFDesigner
//
this.BackColor = System.Drawing.Color.Gainsboro;
<--Add other controls to UC Controls collection-->
this.Controls.Add(this.tsPanel);
this.ForeColor = System.Drawing.Color.Black;
this.Name = "MFDesigner";
this.Size = new System.Drawing.Size(1000, 670);
this.Load += new System.EventHandler(this.MultiFormatDesignerControl_Load);
this.Resize += new System.EventHandler(this.MFDesigner_Resize);
this.pnlToolbox.ResumeLayout(false);
this.pnlProperties.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
Then, in the user control's constructor, I have:
public MFDesigner()
{
InitializeComponent();
<--Other code here-->
ToolStripButton[] openSaveButtonArr = new ToolStripButton[]{
//The createToolStripButton method creates toolstrip buttons using some simple
//parameters.
createToolStripButton("Open", Images.CmdOpen, new EventHandler(this.OnOpen), "Open saved file"),
createToolStripButton("Save", Images.CmdSave, new EventHandler(this.OnSaveToDisk), "Save to disk")
};
ToolStrip openSaveToolStrip = new ToolStrip(openSaveButtonArr);
tspanel.Join(openSaveToolStrip);
<--Other code here-->
}
Since we're creating tool strips and adding them to the toolstrippanel in code, I can't see what it looks like in the designer for the user control. So, I build the dll and I go over to another form in a separate project that consumes the user control from the dll and when the form opens, there is no toolstrip; it simply doesn't appear. Here's the weird thing, though. If I add just one more toolstrip to the panel, the second toolstrip will appear:
public MFDesigner()
{
InitializeComponent();
<--Other code here-->
ToolStripButton[] openSaveButtonArr = new ToolStripButton[]{
//The createToolStripButton method creates toolstrip buttons using some simple
//parameters.
createToolStripButton("Open", Images.CmdOpen, new EventHandler(this.OnOpen), "Open saved file"),
createToolStripButton("Save", Images.CmdSave, new EventHandler(this.OnSaveToDisk), "Save to disk")
};
ToolStrip openSaveToolStrip = new ToolStrip(openSaveButtonArr);
tspanel.Join(openSaveToolStrip, 1);
ToolStripButton[] openSaveButtonArr2 = new ToolStripButton[]{
createToolStripButton("Open2", Images.CmdOpen, new EventHandler(this.OnOpen), "Open saved rpx file 2"),
createToolStripButton("Save2", Images.CmdSave, new EventHandler(this.OnSaveToDisk), "Save to disk 2")
};
ToolStrip openSaveToolStrip2 = new ToolStrip(openSaveButtonArr2);
tsPanel.Join(openSaveToolStrip2, 1);
<--Other code here-->
}
In the code above, the first toolstrip that I create will not appear, but the second one (openSaveToolStrip2) will appear. Incidentally, if I just use the Join overload Join(toolStrip) for both of the toolstrips, nothing appears. Also, if I add toolstrips to other rows, i.e. tsPanel.Join(toolstrip3, 2) or tsPanel.Join(toolstrip4, 3), the toolstrips will appear.
It seems like, for some inexplicable (for me, at least) reason, the first toolstrip that I add never appears but all subsequent toolstrips do. As a workaround, I've been just creating a dummy toolstrip, adding it, then adding all of my real toolstrips. This feels pretty hacky so I'd love to figure out why this is happening. I've tried to follow the documentation on MSDN but I must still be missing something because I can't imagine a bug like this not getting fixed.
Does anybody know what might be going wrong here?

Screenshot of running application with all tool strips inside the tool strip panel
I took your code and removed stray members so that I could compile, or stuff that was not relevant for your issue (these for instance: //private Panel pnlToolbox; //private Panel pnlProperties;). I created the runtime tool strips and joined them to the panel, same as you did. I also provided my own implementation of createToolStripButton since you did not. The third toolstrip uses Image.FromStream and web resources since I lacked the local ones. With or without images I had no malfunction whatsoever ...
Complete example below:
public partial class MFDesigner : Form {
private ToolStripPanel tsPanel;
//private Panel pnlToolbox;
//private Panel pnlProperties;
public MFDesigner ( )
{
InitializeComponent();
//
// first toolstrip
//
ToolStripButton tsbOpen = new ToolStripButton("Open", null, new EventHandler(this.OnOpen), "Open saved file");
ToolStripButton tsbSave = new ToolStripButton("Save", null, new EventHandler(this.OnSaveToDisk), "Save to disk");
ToolStripButton[] openSaveButtonArr = new ToolStripButton[] { tsbOpen, tsbSave };
ToolStrip openSaveToolStrip = new ToolStrip(openSaveButtonArr) { CanOverflow = true };
this.tsPanel.Join(openSaveToolStrip);
//
// second toolstrip
//
ToolStripButton tsbOpen2 = createToolStripButton("Open2", null, new EventHandler(this.OnOpen), "Open saved file");
ToolStripButton tsbSave2 = createToolStripButton("Save2", null, new EventHandler(this.OnSaveToDisk), "Save to disk");
ToolStripButton[] openSaveButtonArr2 = new ToolStripButton[] { tsbOpen2, tsbSave2 };
ToolStrip openSaveToolStrip2 = new ToolStrip(openSaveButtonArr2) { CanOverflow = true };
this.tsPanel.Join(openSaveToolStrip2, 1);
//
// third toolstrip
//
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData("http://my.crestron.eu/images/icons/ico_folder_open.png");
// You must keep the stream open for the lifetime of the Image.
MemoryStream msOpen = new MemoryStream(bytes);
System.Drawing.Image imgOpen = System.Drawing.Image.FromStream(msOpen);
bytes = wc.DownloadData("http://www.njrussians.com/images/save_ico.png");
MemoryStream msSave = new MemoryStream(bytes);
System.Drawing.Image imgSave = System.Drawing.Image.FromStream(msSave);
ToolStripButton tsbOpen3 = createToolStripButton("Open3", imgOpen, new EventHandler(this.OnOpen), "Open saved file");
ToolStripButton tsbSave3 = createToolStripButton("Save3", imgSave, new EventHandler(this.OnSaveToDisk), "Save to disk");
ToolStripButton[] openSaveButtonArr3 = new ToolStripButton[] { tsbOpen3, tsbSave3 };
ToolStrip openSaveToolStrip3 = new ToolStrip(openSaveButtonArr3) { CanOverflow = true };
this.tsPanel.Join(openSaveToolStrip3, 2);
}
ToolStripButton createToolStripButton (string text, Image i, EventHandler eh, string name)
{
return new ToolStripButton(text, i, eh, name);
}
void MFDesigner_Resize (object sender, System.EventArgs e) { }
void MFDesigner_Load (object sender, System.EventArgs e) { }
void OnOpen (object target, EventArgs e) { }
void OnSaveToDisk (object target, EventArgs e) { }
#region Windows Form Designer generated code
/// <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);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent ( )
{
this.tsPanel = new System.Windows.Forms.ToolStripPanel();
this.SuspendLayout();
//
// tsPanel
//
this.tsPanel.Dock = System.Windows.Forms.DockStyle.Top;
this.tsPanel.Location = new System.Drawing.Point(0, 0);
this.tsPanel.Margin = new System.Windows.Forms.Padding(3);
this.tsPanel.Name = "tsPanel";
this.tsPanel.Orientation = System.Windows.Forms.Orientation.Horizontal;
this.tsPanel.RowMargin = new System.Windows.Forms.Padding(3, 0, 0, 0);
this.tsPanel.Size = new System.Drawing.Size(984, 0);
//
// MFDesigner
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.Gainsboro;
this.ClientSize = new System.Drawing.Size(984, 632);
this.Controls.Add(this.tsPanel);
this.ForeColor = System.Drawing.Color.Black;
this.Name = "MFDesigner";
this.Text = "MFDesigner";
this.Load += new System.EventHandler(this.MFDesigner_Load);
this.Resize += new System.EventHandler(this.MFDesigner_Resize);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
}

Related

Access a button from the form in other class in 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.

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

Hiding tab headers in tabControl in winforms

I'm trying to hide tab headers in the tabControl, like it's shown here in this link, but I am getting an error in the designer's code. Once I change both lines, I get this:
Severity Code Description Project File Line
Message The designer cannot process unknown name 'SelectedIndex' at line 43. The code within the method 'InitializeComponent' is generated by the designer and should not be manually modified. Please remove any changes and try opening the designer again. c:\users\krzysztof\documents\visual studio 2015\Projects\DaneUzytkownika3\DaneUzytkownika3\TabController.Designer.cs 44
Severity Code Description Project File Line
Error CS1061 'TabController' does not contain a definition for 'SelectedIndex' and no extension method 'SelectedIndex' accepting a first argument of type 'TabController' could be found (are you missing a using directive or an assembly reference?) DaneUzytkownika3 c:\users\krzysztof\documents\visual studio 2015\Projects\DaneUzytkownika3\DaneUzytkownika3\TabController.Designer.cs 43
Line 43 in the designer's code of the form is:
this.tabControl1.SelectedIndex = 0;
Could someone please tell me, how do I fix it?
TablessTabControl.cs
namespace hiding
{
class TablessTabControl : Form1
{
protected override void WndProc(ref Message m)
{
// Hide tabs by trapping the TCM_ADJUSTRECT message
if (m.Msg == 0x1328 && !DesignMode)
m.Result = (IntPtr)1;
else
base.WndProc(ref m);
}
}
}
Form1.Designer.cs
namespace hiding
{
partial class Form1
{
/// <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.tabControl1 = new TablessTabControl();
//this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.tabControl1.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(31, 12);
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = 0;//line with the error
this.tabControl1.Size = new System.Drawing.Size(200, 100);
this.tabControl1.TabIndex = 0;
//
// tabPage1
//
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(192, 74);
this.tabPage1.TabIndex = 0;
this.tabPage1.Text = "tabPage1";
this.tabPage1.UseVisualStyleBackColor = true;
//
// tabPage2
//
this.tabPage2.Location = new System.Drawing.Point(4, 22);
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
this.tabPage2.Size = new System.Drawing.Size(192, 74);
this.tabPage2.TabIndex = 1;
this.tabPage2.Text = "tabPage2";
this.tabPage2.UseVisualStyleBackColor = true;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.Text = "Form1";
this.tabControl1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private TablessTabControl tabControl1;
//private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
}
}
I have created a project and implemented the tab control as given in your example as follows:
class TablessTabControl : TabControl
{
protected override void WndProc(ref Message m)
{
// Hide tabs by trapping the TCM_ADJUSTRECT message
if (m.Msg == 0x1328 && !DesignMode)
m.Result = (IntPtr)1;
else
base.WndProc(ref m);
}
}
Then upon rebuilding the project I add my new TablessTabControl to a test form using the designer. Within the designer, I can switch between the tabs using the visible headers.
At runtime, the headers disappear as intended. I have two tabs; I am able to select between the tabs by using the following code:
// Selects the first tab:
tablessTabControl1.SelectedIndex = 0;
// Selects the second tab:
tablessTabControl1.SelectedIndex = 1;
Additionally, in Form1.Designer.cs, I have line 48 as follows:
this.tablessTabControl1.SelectedIndex = 0;
which poses no difficulty for me.
Have you tried closing all documents, cleaning the solution, rebuilding and reopening the designer?

Adding menu programmatically

I have been writing a lot of code in Java and find that it is really easy to create either a console or form application. In fact, all one has to do is add a form and display that form. Simple as a cookie, so to speak. But now I have a big project coming up in Visual C# and I have not used it all that much. I think, I am not sure if I am right, but a console application is C# is just that, a console application which cannot accept any mouse action events. I want to be able to add controls to C# from inside of the form, just like in Java. Add a button, or add a menu. But in C# there are several files that open, properties, assemblyinfo.cs, form1.cs, etc. The code below is in form designer.cs.
So where is the best way to add components from the programming point of view and not the design visual stand point of view?
namespace WindowsFormsTestMenuApplication
{
partial class Form1
{
/// <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.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.aToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.bToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.cToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.fileToolStripMenuItem,
this.openToolStripMenuItem,
this.optionsToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(284, 24);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
//
// fileToolStripMenuItem
//
this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.aToolStripMenuItem,
this.bToolStripMenuItem,
this.cToolStripMenuItem});
this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20);
this.fileToolStripMenuItem.Text = "File";
//
// openToolStripMenuItem
//
this.openToolStripMenuItem.Name = "openToolStripMenuItem";
this.openToolStripMenuItem.Size = new System.Drawing.Size(48, 20);
this.openToolStripMenuItem.Text = "Open";
//
// optionsToolStripMenuItem
//
this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem";
this.optionsToolStripMenuItem.Size = new System.Drawing.Size(61, 20);
this.optionsToolStripMenuItem.Text = "Options";
//
// aToolStripMenuItem
//
this.aToolStripMenuItem.Name = "aToolStripMenuItem";
this.aToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.aToolStripMenuItem.Text = "A";
//
// bToolStripMenuItem
//
this.bToolStripMenuItem.Name = "bToolStripMenuItem";
this.bToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.bToolStripMenuItem.Text = "B";
//
// cToolStripMenuItem
//
this.cToolStripMenuItem.Name = "cToolStripMenuItem";
this.cToolStripMenuItem.Size = new System.Drawing.Size(152, 22);
this.cToolStripMenuItem.Text = "C";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 262);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "Form1";
this.Text = "Form1";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem aToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem bToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem cToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem optionsToolStripMenuItem;
}
}
Sounds somehow like a general design/approach question to me.
Why don't you use WPF over WinForms? Gives you a quite handy designer in Visual Studio. You can comfortably build your GUI in WYSIWYG-style. Supports data binding, which - once familiar with - is pretty convenient.
However, later you can still add controls etc. at runtime, see Breems answer.
Note: If you use WPF, you need to use the Windows's dispatcher if you want to add controls from another thread than the Windows's one.
Are you trying to add controls at runtime? If so, as SLaks stated, you will simply need to create a new instance of the control and add it to your form.
// Add a menustrip to the form.
MenuStrip menuStrip = new MenuStrip();
menuStrip.Dock = DockStyle.Top;
this.Controls.Add(menuStrip);
Otherwise, why not utilize the visual designer to add controls to your form?
WinForms controls are regular objects, just like AWT or Swing.
You can create a new ToolStripItem(), set its properties, then add it to a DropDownItems collection.

Categories

Resources