C# - Don't bring form to front - c#

My apps use a timer that display a form after some seconds.
When I minimize my apps to do other stuff, the timer is still active (I'm ok with that) and the form bring to front over all my windows with focus on it (normal behavior).
I want that the new form open above my main apps but not above all my windows.
In the main form, I call the new form like this :
MRIS.EVENT_BOX form1 = new MRIS.EVENT_BOX();
form1.Owner = this;
form1.ShowDialog();
I manage to remove the focus problem by adding this in the EVENT_BOX :
protected override bool ShowWithoutActivation { get { return true; } }
I also check that TopMost is set to false in the new form.
But the new form is still show above all the others (without focus this time...).
I check some other questions but cannot manage to find something useful.
Some people talk about visible form ?
If you can help me ?
Thanks

You need to call form1.Show(); if you don't want to bring it to front
form1.Show();
//form1.BringToFront() You may need to call this if you want to being it to front
form1.ShowDialog() shows the form as dialog which means it will be shown on top of parent form. You can check more details on this here

Related

C# Disable Form

I've created a menu form with two checkboxes. When I select one of them, I want to disable another form. I tried to write this code:
void CheckBox1CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked == true){
checkBox1.Checked=true;
checkBox2.Checked=false;
classificheForm cf=new classificheForm();
cf.Enabled=false;
classificheJunioresForm cjf=new classificheJunioresForm();
cjf.Enabled=false;
}
}
but doesn't work, indeed forms aren't disable. How can I fix it?
You are creating a new Form and immediately disabling it:
classificheForm cf=new classificheForm();
cf.Enabled=false;
Instead you should use the reference to the Form you want to disable. For example if in the constructor you create the form:
classificheForm cf;
public SomeClassConstructor()
{
cf=new classificheForm();
}
Then in your event you would just do:
cf.Enabled=false;
Note that you can also hide and show forms like:
cf.Hide();
cf.Show();
Note that needing to disable a Form sounds like an XY problem. If you don't need the form anymore close it or hide it. Also only use Forms when they are needed etc...
If you need to disable a main Form whilst you use a dialog form it is best to call
dialog.ShowDialog();
as this will block users being able to interact with the main Form until they have closed the dialog one.
You can easily hide a Form
classificheForm cf=new classificheForm();
cf.Show();
classificheJunioresForm cjf=new classificheJunioresForm();
cjf.Hide();
Or what do you mean with "disable"?

Form closing before new shows

Hello I'm making my first Windows Forms app in C# using Visual Studio and I have a little problem.
While I'm opening a new form and closing the previous one, when I run the app it looks like it's closing the previous form before it opens a new one.
It doesn't look good and I want to avoid it.
UserPanel MDIUserPanel = new UserPanel(Username);
MDIUserPanel.MdiParent = this.MdiParent;
MDIUserPanel.Show();
this.Close();
I don't know what is going wrong. I will be thankful for any help.
Wirth regards,
DarQScreaM
#Edit
This doesn't seem to be the case actually. Propably its that :
I have 3 forms MainForm, Login, LoggedUser.
MainForm is MDI container with FormBorderStyle set on Fixed Single
Login is child of MainForm with FormBorderStyle set on None
LoggedUser is child of MainForm with FormBorderStyle set on None
When application is runned Login form is created in MainForm. MainForm is never closed since its container.
But when i move from Login form to LoggedUser form and vice-versa its created with FormBorderStyle = Fixed Single (normal windows window) and after 0.5~second its changed into None.
Editing it into that didn't really help :
MDIUserPanel.FormBorderStyle = FormBorderStyle.None;
MDIUserPanel.Show();
#Edit2
This change fixed it for me. I don't know why setting it on Form properties didn't work properly. It looked like form was created as FormBorderStyle.FixedSingle and then it was changed into FormBorderStyle.None. If I made this manually in Load it worked but U had to fix the size of my window too. It doesn't seem to be good though. It should work from the beginning since Form properties in Designer are like that from the very beginning.
private void UserPanel_Load(object sender, EventArgs e)
{
this.FormBorderStyle = FormBorderStyle.None;
this.Size = new Size(649, 357);
}
You can use the form's Shown event to ensure that the new form have been showed before you close the old one.
UserPanel MDIUserPanel = new UserPanel();
MDIUserPanel.Shown += ((s, ee) =>
{
this.Close();
});
MDIUserPanel.Show();
If this form you are trying to close, is the main form that opens when you run your application, then that's the reason. Closing the main form will exit your application. Try instead to just hide this form instead of closing it. And to make sure you can exit your application ('cause you've hidden your main form), just override the closing event of your current form, and put an "Application.Exit()" in it.
Hope this helps you !
First Step:
this.Hide();
Second Step:
MDIUserPanel.Show();

Why calling Hide in a child form's FormClosing event handler hides the parent form?

When Form2 is closed, via it's X button, the Main form is sometimes hidden as well, but not always. Often times the Main form is hidden after initial 'newForm' button click and other times many open-close operations are required before the Main form gets hidden on Form2's closing. Why is this happening? Why is it irregular?
This is a small test code for a larger application I'm working on. In that application a thread continuously reads the network stream and when a particular message is encountered a modal form is displayed. The user can close that modal form or it can be told to close itself by a different network message. In this event, to give the user some time to view the data that the form is displaying I implemented a delayed form closing for that form. When the form is running its delay closing code, another message can come in over the network that will open up a new instance of this form in which case, I observed, that once the timer of the original form runs out, the original form is left displayed until the new instance is closed. Calling Hide in the FormClosing event handler closes the original form if more than one instances of it are running, but it has this side effect of hiding the entire application (the Main form) when the last instance of this form is closed, either by the user or by the delayed closing code. And again, the entire application is not always hidden, but it does happen.
//Main form's 'newForm' button
private void btn_newForm_Click(object sender, EventArgs e)
{
Form2 f = new Form2();
f.ShowDialog();
}
public partial class Form2 : Form
{
private void Form2_FormClosing(object sender, FormClosingEventArgs e)
{
Hide();
}
}
Update (from the application I'm working on):
The problem is shown visually below. The top part of the picture, labeled "A", represents the situation where the first modal dialog (greyed out) was instantiated and it is in the process of being auto closed after 4 seconds have elapsed. The second instance (blue window heading) is active and awaiting input. In the lower part of the picture, labeled "B", the counter to closing of the first instance has completed, yet the first instance remains visible. Adding Hide does not change picture "A" but picture "B" would only be showing the active modal dialog, which is what I want. If Hide is not used and we have the case shown in "B", once the active modal dialog is closed the inactive dialog will disappear together with the active one, but no sooner. At this time my main form will be hidden as well, sometimes.
Your main form doesn't get hidden, it disappears behind another window. The flaw in your code is that for a brief moment none of your windows can get the focus. Your main window can't get the focus, it got disabled by your dialog and won't get re-enabled until the dialog is fully closed. Your dialog can't get the focus, you hide it. So Windows goes looking for another window to give the focus to and can only pick a window owned by another application. Like Visual Studio, nice and big so your main window is well covered by it.
Not sure what you are trying to do, it doesn't make sense to call Hide() since the dialog will close a couple of microseconds later. Just delete the statement.
I am not sure if I am right but maybe you forgot to add e.Cancel = true; to your closing event.
Second, I think using a modal form is only usefull when you expect an action like OK or CANCEL from user, that is where DialogResults comes handy. It sounds strange if this happens time to time not all the time! maybe you can try like this:
//Main form's 'newForm' button
//Define form in your mainform
private Form2 f;
private void btn_newForm_Click(object sender, EventArgs e)
{
if(f != null) { f.Show(); return; }
f = new Form2()
f.FormClosing += delegate { f.Hide(); };
f.Show();
}
I know the topic is quite old, but I recently had to look for answers for this precise question.
Why hiding the (child modal) form instead of closing it ?
I may be wrong, but I think that in some cases, hidding the modal child form instead of closing it is sometimes useful.
For example, I'm using a class that is a custom tree of grids. Think of something like an Excel Document with multiples tables (sheets) and each table can have child tables. A very powerful manner to store datas that can be used by multiple objects and multiple forms at a time.
Now, this "TreeTable_Class" object has an inbuilt custom form that actually shows the content of one of its tables at a time in a GridView, and you can select which table to show by selecting it in a Treeview. You can see here that the "Database Editor" is actually and MDI Form that can load the Form from any TreeTable_Class.
And this is the Form I use to edit the content of a Cell for a given (selected) Table (I've chosen another cell with long text content from another table in this database)
Now, when you choose to close the custom form instead of hiding it, that form will be unaccessible, you can't show it anymore, and you get an exception (no instance of the object) Somewhat, it isn't disposed yet (so the check If MyForm Is Nothing Then... is useless) I know I have to implement the GarbageCollector and dispose the Child Form manually, but it's outside the scope of this topic.
Anyway, my class could use a large amount of memory, of datas, and if I had to rebuilt ALL the contents each time I want to show a new instance of that form, that would be a large amount of workload in my application. That's why I have chosen to hide the form instead of closing it until the main application exits or when a specific CloseFormAndDispose() method is explicitly called, either by the program, or if I make this option available for the user via an user interface.
Workaround try :
This is the workaround I've found to override the "form replaced by another because none of the parent/child ones could be retrieved" :
Sorry, I'm in VB.. but you can use a tool to convert this to C#, or do it manually, it's pretty simple..
// This is the child, a Cell Editor that can edit the content of a Cell.
Protected WithEvents _CellEditor As CellEditor_Form = Nothing
This Editor form is a member of TreeTable_Form, a form that can actually show and edit the content of the whole Database File (a single file)
And this TreeTable_Form class contains a routine that handles CellEditor closing event
Public Partial Class TreeTable_Form
// Sorry. The "WithEvents" in C# is a litte bit complex to me... So, in VB :
Protected WithEvents _CellEditor As CellEditor_Form = Nothing
// ...
// CellEditor handling method (I used a Code converter...) :
// The original VB declaration is :
// Protected Sub RecallFormAfterCellEditorHidden() Handles _CellEditor.Closed
// You'll have to write specific Event handler for _CellEditor object declared above...
protected void RecallFocusAfterCellEditorHidden()
{
Application.DoEvents();
this.Focus();
}
End Class
This tiny protected void RecallFormAfterCellEditorHidden() method in your Class (if you are using a class that contains Forms) or in your Main From, assuming that your main form contains the child forms (dialogs) will try to force the focus on your Application or MainForm...
By the way, TreeTable_Form is actually a component of TreeTable_Class. The later is an object that can be used anywhere you want. In a Main Form Application, in another Class, in a dialog, anywhere... and could be passed by reference to share its contents between several items. And this TreeTable_Class contains a RecallFocusAfterTreeViewerHidden() method that handles the closing of that form. That means, the Form or Application that actually uses the class will get the focus each time you close the its child Form. I've made it that way to get an object that could be used anywhere
We still get problems !
However, this method will make your application flicker a bit each time you close your child dialog, and doesn't succeed at 100% ! Sometimes, my parent form still disappear from screen and gets struck behind another window. Alt+TAB wont helt either. But this happens less than without this method trick. I don't have any better answer at this time, still searching... I'll come back here if I find out how. I'm using this custom made application in my work to write memos during meetings for example, and produce PV (procès verbal - french sorry) in PDF or DOCx on the fly...
And I'm sorry, I'm in VB, not C#. Hope this helps a little, until we find a better workaround for this...

How to bring "all forms" to foreground (WindowsMobile/C#)

(C# / WindowsMobile 6)
Let's take an application with 3 STATIC forms: Form1, Form2, Form3, where Form1 opens Form2 by calling Form2.Show(), and Form2 does the same with Form3. Form2 and Form3 have a "Exit" button, that just hides the form (not "close", just hide).
So, we execute these steps:
open the application;
go to Form2, by clicking "Form2" button on Form1;
go to Form3, by clicking "Form3" button on Form2;
open File Explorer, and "re-open" application by clicking on it's file. Form3 appears;
hide Form3 by clicking on "Exit" button on Form3 ( this.Hide() ). That's the problem: file explorer appears instead Form2.
I don't want to call "callingform".Show() every time I hide a form. This "works", but file explorer screen appears after "this.Hide()" and before "callinform.Show()" and I need to "control" who's calling who.
How to solve this? Is there any way to bring all application's form to foreground in the same order they appeared?
Thanks in advance.
There really isn't a way. You could implement a way to store forms in a similar way to the first answer, but when you switch you need to do:
"callingform".BringToFront();
"callingform".Show();
That will put all of your forms in front of Explorer.
You might need to do some investigation into this, but off the top of my head you could try looking at the Application.Forms[] collection.
Maybe someone can confirm or deny this but I think usually, Application.OpenForms[0] will be the main/initial form with subsequent Form appearances being in Application.OpenForms[1], Application.OpenForms[2], etc...
So you could simply try navigating backwards through this Forms collections.
Something like (or a variation of),
public void BringLastOpenedFormToFront()
{
if(Application.OpenForms.Count > 0)
{
Form form = Application.OpenForms[Application.OpenForms.Count - 1];
BringToFront(form); // your bring to front method.
}
}
This would allow you to ensure the last Form that appeared was brought to the front and immediately visible to the user. Let me know if you need any clarification.
Link to MSDN:
http://msdn.microsoft.com/en-us/library/system.windows.forms.application.openforms.aspx

How to know if the Form App open or not c#

Does anyone know how can I know if the Windows Form Application (C#) is open or that the client closed it?
(In my App I have a Windows Form Application (Form1) that allow the user to open another Forms (Form2). I want to know if the Form2 is open or close.)
I need to know that because I run the Form2 from a thread, and I want to make the thread runnig until the user close Form2.
Many thanks!
You can check if a form of a given type is open in your application like this (using LINQ):
if (Application.OpenForms.OfType<Form2>().Count() > 0)
{
// there is an instance of Form2 loaded
}
You need to elaborate on your question a bit more. Are you talking about monitoring the application from another application? Or that one form needs to know if another one is open? Or a form needs to know when another form closes?
There are a couple of ways to monitor forms closing within the same application.
Calling ShowDialog() on your form instead of Show() will ensure that code following the ShowDialog() call doesn't get executed until the user closes the form.
The Form class has a Visible property, which returns true/false depending on whether the form is visible or not.
As for the application itself, there is an ApplicationExit event on the static Application class which gets called just before the application closes so you could listen to that event if, for example, you need to perform some clean-up on exit.
If you want to run only single instance of application, check this link.
There you will also see how to check whether a process is still active.
If you mean MDI application with its child forms:
private Dictionary<Type, Form> SingleInstanceForms = new Dictionary<Type, Form>();
public Form ActivateForm<T>() where T : Form, new()
{
Cursor.Current = Cursors.WaitCursor;
if (!this.SingleInstanceForms.ContainsKey(typeof(T)))
{
T newForm = new T();
//setup child
newForm.MdiParent = this;
newForm.WindowState = FormWindowState.Maximized;
//newForm.Icon = Icon;
newForm.FormClosed += new FormClosedEventHandler(delegate(object sender, FormClosedEventArgs e)
{
this.SingleInstanceForms.Remove(sender.GetType());
});
this.SingleInstanceForms.Add(typeof(T), newForm);
newForm.Show();
this.Refresh();
}
Form formToActivate = this.SingleInstanceForms[typeof(T)];
formToActivate.Activate();
Cursor.Current = Cursors.Default;
return formToActivate;
}
this will create the form child if hasn't been created yet and activate it if it has been created.
sample: ActivateForm<dlgChildOne>();

Categories

Resources