Usercontrol removal - c#

My problem is the following. I have a form which when it loads up invokes a user control onto it. On the user control I have buttons. With the buttons I would like to make the user control disappear with all the buttons and picture boxes on it and make a new user control appear. The appear part is all right but I can't make the user control disappear with all the objects on it.
Can you help me with this one?
So the dispose method closes the usercontrol well, but then I can't make the new user control appear. Code is like this:
akusztikusUserControl auc = new akusztikusUserControl();
public menuUserControl()
{
InitializeComponent();
}
private void akusztikus_btn_Click(object sender, EventArgs e)
{
this.Dispose();
this.Controls.Add(auc);
}
}

Have you considered using Panel or a TableLayoutPanel control ? In both cases you can remove controls through the .controls.remove option
You can then just add the user control to the panel / tablelayoutpanel whenever you need to use it again.

Related

.NET C# Using TreeView in WinForms like tab control

I want to use TreeView in my software so when user clicks a node, the content of the Form will be changed. Example in this picture, but also I want to grab user input from all forms.
WinForms TreeView example
https://youtu.be/9BdYzMDxl9M?t=46
TreeView -> Node -> User Click -> Display Form_X in the GroupBox
I tried but I could not find related resources on this topic so I posted this question. Thank you for your help
Don't use forms as child controls. User controls exist specifically for that so use them. You add a user control to a project in the same way as you do a form, simply selecting a different menu option. You then design it and add code to it just as you would a form. Once you build your project, the user control will appear in the Toolbox and you can use it just like you would any other control. You then have a couple of options for how to handle switching controls via the TreeView.
If the number of controls is fairly small, you can add one of each to the GroupBox in the designer, so they all exist all the time. You would probably want to set the Dock property of each to Fill, so they all fill the parent GroupBox. In the Load event handler of the form, you can assign each user control instance to the Tag property of the corresponding TreeNode. When the user selects a node, you get the user control from its Tag property and call BringToFront on it, so the user will see it and it will hide all the other user controls, e.g.
private void Form1_Load(object sender, EventArgs e)
{
var nodes = treeView1.Nodes;
nodes[0].Tag = userControl1;
nodes[1].Tag = userControl2;
nodes[2].Tag = userControl3;
}
private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
{
var userControl = treeView1.SelectedNode.Tag as Control;
userControl?.BringToFront();
}
Because all the controls exist all the time, you can load all the data at the start and save all the changes at the end and not have to transfer any data when the selection changes.
If the number of controls is larger, you might want to show just one at a time. That becomes more complex because, when the selection changes, you have to make sure that any changes in the current user control are remembered, remove the existing control and then create and load the new control. Because the process is more complex, there are more options about exactly how to implement it. For that reason, I won't go into specifics here. If you want to go that way, you need to consider those options and how they relate to the specifics of your application and then decide how you want to implement the process. If you do that and encounter an issue along the way, that would be another question.
What have you tried? I am confident there are many ways to achieve what you describe. Since you mentioned a TabControl have you considered using a TabControl without the Tabs and manually switch to the proper tab page whenever the tree view node is clicked.
Something like…
private void Form1_Load(object sender, EventArgs e) {
tabControl1.Appearance = TabAppearance.FlatButtons;
tabControl1.ItemSize = new Size(0, 1);
tabControl1.SizeMode = TabSizeMode.Fixed;
}
private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {
if (e.Node.Name == "TabPage1") {
tabControl1.SelectTab("TabPage1");
}
else {
tabControl1.SelectTab("TabPage2");
}
}

how to access a user define controls iner controls in parent form

I'm new to windows forms programming so my question may sound little strange.
I have created a user define control (countdown timer) now I'm creating n no of it dynamically in a form by Click of a button (Add new timer) its working well and good.
Here is the Creation Code
private void Addnew_Click(object sender, EventArgs e)
{
UserControl1.userControl11 = new UserControl1();
flowLayoutPanel1.Controls.Add(userControl11);
}
My user control has a Reset button that reset all the content inside the user define control.
it is also working, but What I want Allow user to reset all the Created timers using the “Reset All” button on the form.
Okay one way to do this.
Create a List<UserControl1> private member on your form called say _myUserControls
In your Addnew Handler add it to the list.
If you have a remove button, don't forget to remove from _myUserControls as well.
Add a Reset method to your UserControl1, that does what it needs to do.
Then in your Reset all button click handler
foreach(UserControl1 ctrl in _myUserControls)
{
ctrl.Reset();
}
Jobs a good 'un
The answer I referred you to in comments, would be a way of finding all instances of your UserControl1 class, so you wouldn't need an internal list.

Adding close button on tab header in c# winforms [duplicate]

My scenario is the following:
I am working on a winforms application in C# that has a button inside the main page of a tabcontrol that will generate another tabpage each time that it is clicked. Each new tabpage will contain a layout defined by a user control.
My Questions are:
How can I allow the user to then close one of the tabs that were created dynamically at runtime?
How might I go about modifying the tabcontrol itself so that it has a small 'X' in each tab that the user may click on in order to close that particular tab? (Like Firefox has)
How can I expose the SelectedIndex property of the tabcontrol to the user control if I want to close the tab with a button inside the user control instead?
I found this code and was very helpful to me:
private void tabControl_MouseUp(object sender, MouseEventArgs e)
{
// check if the right mouse button was pressed
if(e.Button == MouseButtons.Right)
{
// iterate through all the tab pages
for(int i = 0; i < tabControl1.TabCount; i++)
{
// get their rectangle area and check if it contains the mouse cursor
Rectangle r = tabControl1.GetTabRect(i);
if (r.Contains(e.Location))
{
// show the context menu here
System.Diagnostics.Debug.WriteLine("TabPressed: " + i);
}
}
}
}
TabControl: How To Capture Mouse Right-Click On Tab
I created a derived tab control about one year ago. I am not going to post the source here, because it's about 700 lines long and coded quite messy. Maybe I will find some time to clean the code up and then release it here. For now I will briefly outline the way it is build.
Each tab page has a 'X' icon to the left of the title and the tab pages support reordering by drag and drop and moving them between multiple tab control.
I choose the easy way to get the icon on the tab pages. The tab control has the TabControl.ImageList property and a tab page has a TabPage.ImageIndex property. So I just added three icons to a image list - normal, hover, pressed - and process the mouse events.
With TabControl.GetTabRect() you can test if the mouse is over a specific tab pages and with some math you find if it is over the icon. Then you just need to change the icon depending on the mouse button state and eventually remove the tab page under the mouse if the button was pressed.
The main problem with this solution is, that calculating if the mouse is over the icon requires to know where the icon is painted relative to the tab page and this might change with a new windows version. And the icon is to the left of the title, but that does not look too bad.
I did the following:
on the create (add) TabPage stage, I added a toolStrip
ToolStrip ts = new ToolStrip();
ts.Dock = DockStyle.Top;
ts.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
Then, create the X button and add it to toolstrip
ToolStripButton ToolStripButton = new ToolStripButton("X");
ts.Items.Add(ToolStripButton);
create an event on clicking the X button
ToolStripButton.Click += new EventHandler(ToolStripButton_Click);
add toolstrip to the tabpage
tabControl1.TabPages[curenttabpage].Controls.Add(ts);
now for the ToolStripButton_Click is as follows:
void ToolStripButton_Click(object sender, EventArgs e)
{
ToolStripButton t = (ToolStripButton)(sender);
ToolStrip ts = t.Owner;
TabPage tb = (TabPage)
(ts.Parent);tabControl1.TabPages.Remove(tb);
}
Maybe it is not as you want, but it will work well.
I created a setup that is similar.
Each control that is added to the tab page at runtime is derived from a special base control I created. This base control has a close button (along with some other features such as safe to close flag).
Close tab code I'm using on my base control:
TabPage tabpage = (TabPage)this.Parent;
TabControl tabControl = (TabControl)tabpage.Parent;
tabControl.TabPages.Remove(parent);
I know this is an old thread but I did find this link that will allow you to "hide" tabs in an array and then you can just re-load the tabs you want at run time. I added this more for a place I can easily find it again.
This code might help throgh closing the tab controls with middle mouse click :
private void tabControl1_MouseDown(object sender, MouseEventArgs e)
{
if (e.Button != System.Windows.Forms.MouseButtons.Middle)
return;
for (int i = 0; i < MainTabControl.TabPages.Count; i++)
{
if (this.MainTabControl.GetTabRect(i).Contains(e.Location))
{
this.MainTabControl.TabPages.RemoveAt(i);
return;
}
}
}
It´s works!
TabPage tabpage = (TabPage)this.Parent;
TabControl tabControl = (TabControl)tabpage.Parent;
tabControl.TabPages.Remove(tabpage);

Dynamic Naming of C# Form Elements

My app needs to be able to dynamically create new form elements and work with them. Right now I have a panel with buttons and labels in it. I need to be able to make a duplicate of this and show it in my app and then work with it.
For example, I have panel1. Inside are label1, button1, and button2.
Label 1 just counts up by seconds.
When you click button1, label1 starts counting up. When you click button2, the timer stops.
My problem is that I need to be able to duplicate panel1 many times and still have the new buttons correspond to the correct labels.
On button_click
private void button1_Click(object sender, EventArgs e)
{
Button theSender = (Button)sender;
Panel parentPanel = (Panel)theSender.Parent;
}
From here, I can't target any of the child control . I'm used to targeting and handles in jQuery, so I don't even know the correct C# terminology for how to explain myself.
If understand your problem correctly, I recommend you to make a Usercontrol with a Panel and fill it with your Label, Button and whatever. Write the events for your buttons in the usercontrol. Then introduce this usercontrol in your form and it should work. You can introduce any number of usercontrols in your form and each button will behave/work for the label in that usercontrol only.
As you mentioned you are new in winforms and you are not sure what I am saying, let me know and I will help if I get enough time.
Hope it helps.
Children of a control can be accessed using Control.Contrtols collection, e.g. to access button on a form:
Button btn = this.Controls["button1"];
But that is only true if button1 is placed directly on your form and button1.Name property is set to "button1" (designer does that automattically, if you are creating your controls dynamically, you have to take care of naming your controls yourself.)
You can also enumerate child controls of any control, e.g. child controls of panel1:
foreach(Control c in panel1.Controls)
{
// do something, e.g.
if(c is Label){//do sth...}
if(c.Name.Equals("label1") && c is Label)
{
Label l = c as Label;
}
}
and as #rapsalands said, UserControl may be an answer for you.
I would create a user control (UserControl) for this.
Check this article for more explanation about the difference between Control and UserControl.
Controls and UserControls are easy to duplicate and the full functionality is there.
You can create new UI Controls in code as you would any other object: Button b = new Button();
Then you can add them to the form using form.Controls.Add(b). You'll need to position and size the controls as well (there are properties available for doing this) and hook up your event handlers using b.Clicked += form.button_click;.
To see an example of this, you can try having a look at the designer.cs file that is generated in Visual Studio (don't make changes to it, just have a look). It will look quite complex at first but might go some way to helping demystify Windows Forms, and you will be able to find all of the properties you need to set in there.
Whenever you update something in the designer, Visual Studio generates new code and puts it in the designer.cs file. The entire form is set up in the InitializeComponent() method, which is called from the constructor of your form. You should be able to copy some of that code and with a couple of modifications use it for creating your own dynamic UI elements.
As rapsalands says, it sounds like a user control would be useful in this situation, as it will help encapsulate the functionality you're after. However that may take a bit of time to get your head round and you may find it simpler for now to do everything in your form without creating a new control.
So you are a beginner and need some time to understand Usercontrol as I mentioned in my previous answer. Use a for loop in the Constructor or Load event of your form to dynamically generate controls.
Panel panel;
Label label;
Button button1;
Button button2;
for(int i = 0; i > count; i++)
{
panel = new Panel();
button1 = new Button();
button2 = new Button();
label = new Label();
panel.Controls.Add(button1);
panel.Controls.Add(button2);
panel.Controls.Add(label);
Controls.Add(panel);
button1.Click += Event1;
button2.Click += Event2;
}
private void Event1()
{
label.Text = "Button 1 Clicked."
}
private void Event2()
{
label.Text = "Button 2 Clicked."
}
This way certainly you can create as many controls you want and will also serve your purpose. Use some variables to locate the panel controls appropriately. Set any properties you wish to add in the for loop for the controls.
This is just an alternative for my previous answer. I still recommend the previous answer given by me. This code is dummy and not tested.
Hope it helps.

Is there any way to detect a mouseclick outside a user control?

I'm creating a custom dropdown box, and I want to register when the mouse is clicked outside the dropdown box, in order to hide it. Is it possible to detect a click outside a control? or should I make some mechanism on the containing form and check for mouseclick when any dropdownbox is open?
So I finally understand that you only want it to close when the user clicks outside of it. In that case, the Leave event should work just fine... For some reason, I got the impression you wanted it to close whenever they moved the mouse outside of your custom dropdown. The Leave event is raised whenever your control loses the focus, and if the user clicks on something else, it will certainly lose focus as the thing they clicked on gains the focus.
The documentation also says that this event cascades up and down the control chain as necessary:
The Enter and Leave events are hierarchical and will cascade up and down the parent chain until the appropriate control is reached. For example, assume you have a Form with two GroupBox controls, and each GroupBox control has one TextBox control. When the caret is moved from one TextBox to the other, the Leave event is raised for the TextBox and GroupBox, and the Enter event is raised for the other GroupBox and TextBox.
Overriding your UserControl's OnLeave method is the best way to handle this:
protected override void OnLeave(EventArgs e)
{
// Call the base class
base.OnLeave(e);
// When this control loses the focus, close it
this.Hide();
}
And then for testing purposes, I created a form that shows the drop-down UserControl on command:
public partial class Form1 : Form
{
private UserControl1 customDropDown;
public Form1()
{
InitializeComponent();
// Create the user control
customDropDown = new UserControl1();
// Add it to the form's Controls collection
Controls.Add(customDropDown);
customDropDown.Hide();
}
private void button1_Click(object sender, EventArgs e)
{
// Display the user control
customDropDown.Show();
customDropDown.BringToFront(); // display in front of other controls
customDropDown.Select(); // make sure it gets the focus
}
}
Everything works perfectly with the above code, except for one thing: if the user clicks on a blank area of the form, the UserControl doesn't close. Hmm, why not? Well, because the form itself doesn't want the focus. Only controls can get the focus, and we didn't click on a control. And because nothing else stole the focus, the Leave event never got raised, meaning that the UserControl didn't know it was supposed to close itself.
If you need the UserControl to close itself when the user clicks on a blank area in the form, you need some special case handling for that. Since you say that you're only concerned about clicks, you can just handle the Click event for the form, and set the focus to a different control:
protected override void OnClick(EventArgs e)
{
// Call the base class
base.OnClick(e);
// See if our custom drop-down is visible
if (customDropDown.Visible)
{
// Set the focus to a different control on the form,
// which will force the drop-down to close
this.SelectNextControl(customDropDown, true, true, true, true);
}
}
Yes, this last part feels like a hack. The better solution, as others have mentioned, is to use the SetCapture function to instruct Windows to capture the mouse over your UserControl's window. The control's Capture property provides an even simpler way to do the same thing.
Technically, you'll need to p/invoke SetCapture() in order to receive click events that happen outside of your control.
But in your case, handling the Leave event, as #Martin suggests, should be sufficient.
EDIT: While looking for an usage example for SetCapture(), I came across the Control.Capture property, of which I was not aware. Using that property means you won't have to p/invoke anything, which is always a good thing in my book.
So, you'll have to set Capture to true when showing the dropdown, then determine if the mouse pointer lies inside the control in your click event handler and, if it doesn't, set Capture to false and close the dropdown.
UPDATE:
You can also use the Control.Focused property to determine if the control has got or lost focus when using a keyboard or mouse instead of using the Capture with the same example provided in the MSDN Capture page.
Handle the Form's MouseDown event, or override the Form's OnMouseDown
method:
enter code here
And then:
protected override void OnMouseDown(MouseEventArgs e)
{
if (!theListBox.Bounds.Contains(e.Location))
{
theListBox.Visible = false;
}
}
The Contains method old System.Drawing.Rectangle can be used to indicate if
a point is contained inside a rectangle. The Bounds property of a Control is
the outer Rectangle defined by the edges of the Control. The Location
property of the MouseEventArgs is the Point relative to the Control which
received the MouseDown event. The Bounds property of a Control in a Form is
relative to the Form.
You are probably looking for the leave event:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx
Leave occurs when the input focus leaves the control.
I just wanted to share this. It is probably not a good way of doing it that way, but looks like it works for drop down panel that closes on fake "MouseLeave", I tried to hide it on Panel MouseLeave but it does not work because moving from panel to button leaves the panel because the button is not the panel itself. Probably there is better way of doing this but I am sharing this because I used about 7 hours figuring out how to get it to work. Thanks to #FTheGodfather
But it works only if the mouse moves on the form. If there is a panel this will not work.
private void click_to_show_Panel_button_MouseDown(object sender, MouseEventArgs e)
{
item_panel1.Visible = true; //Menu Panel
}
private void Form1_MouseMove(object sender, MouseEventArgs e)
{
if (!item_panel1.Bounds.Contains(e.Location))
{
item_panel1.Visible = false; // Menu panel
}
}
I've done this myself, and this is how I did it.
When the drop down is opened, register a click event on the control's parent form:
this.Form.Click += new EventHandler(CloseDropDown);
But this only takes you half the way. You probably want your drop down to close also when the current window gets deactivated. The most reliable way of detecting this has for me been through a timer that checks which window is currently active:
[System.Runtime.InteropServices.DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
and
var timer = new Timer();
timer.Interval = 100;
timer.Tick += (sender, args) =>
{
IntPtr f = GetForegroundWindow();
if (this.Form == null || f != this.Form.Handle)
{
CloseDropDown();
}
};
You should of course only let the timer run when the drop down is visible. Also, there's probably a few other events on the parent form you'd want to register when the drop down is opened:
this.Form.LocationChanged += new EventHandler(CloseDropDown);
this.Form.SizeChanged += new EventHandler(CloseDropDown);
Just don't forget to unregister all these events in the CloseDropDown method :)
EDIT:
I forgot, you should also register the Leave event on you control to see if another control gets activated/clicked:
this.Leave += new EventHandler(CloseDropDown);
I think I've got it now, this should cover all bases. Let me know if I'm missing something.
If you have Form, you can simply use Deactivate event just like this :
protected override void OnDeactivate(EventArgs e)
{
this.Dispose();
}

Categories

Resources