FolderBrowserDialog not showing up on second form - c#

Ok, this is the main essence of what I am trying to achieve and the symptoms of what it is doing.
I have a main windows form. On this form the user can click on a button that will open up a new and seperate form. This form will have a button that is supposed to display a FolderBrowserDialog. Instead it simply locks up form2 and never displays anything.
Here is essentially the code I have dealing with the form etc.
This is in the first form that is loaded after i do some uninteresting things.
FORM1.cs
//do stuff
//In a button.click method I do the following
Application.Run(new Form2(myParameters1, 2, 3));
This is the second form that is called from the first form
FORM2.cs
//do more stuff with the parameters on load
//user clicks on a button
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = Environment.SpecialFolder.Desktop;
fbd.Description = "This is the browser dialog box";
if(fbd.ShowDialog() == DialogResult.OK)
{
//do stuff
}
}
After I click on the button the dialog box does not show up and the form2 gets locked from doing anything.
I have also attempted changing the
fbd.ShowDialog()
To
fbd.ShowDialog(Form2.ActiveForm)
with the same results.
Any help would be appreciated! If you need more info let me know and I can try to provide all that I can.
EDIT
I forgot to mention (and actually completely forgot) That the method that opens up the second form is a seperate thread.
So the first form starts a thread, which opens the second form, which is supposed to open a dialog which it is not. Now i think it has to do with the threading..

I have figured out my issue. It ended up being that the thread from Form1 that was opening Form2 was not able to open DialogBoxes because it was seperate from the UI thread entirely.
I ended up working around using that thread and just eliminated it completely which solved my problem. The dialog box opened up just as I wanted.
Thank you all for the responses though! They did help me figure out a few other things I failed to do correctly.

I had similar problem. Main GUI thread was creating a backgroundworker thread to write to database but when background thread is failed used to show a custom control dialog to save exception file. THis custom dialog was shown correctly however Browse button on it to open folderBrowserDialog to save the exception file wouldn't show. My custom control would show "Not Responding" in its title bar.
What I did was instead of calling Custom Control directly I made it call on UI thread itself
like this.
void DBThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
{
this.Invoke(new CrossThreadExceptionHandler(CatchInterThreadException), e.Error);
}
}

Related

How to bring the main form back to the front after the file open dialog is closed

My C# application starts by opening a form. In the constructor for that form I "showDialog" an openfiledialog. After selecting a file to open, the openfile dialog closes, the file is loaded and the contents displayed in the main form but the main form is buried behind every other open window on my desktop.
I have to find it in the task bar and bring it to focus. I just started the application, I want the form to have focus.
I have written other applications that do not use the openfiledialog and when I start them the main form opens with focus as you would expect.
How do I make the main form get focus after the openfiledialog closes?
I have tried
this.focus(),
this.activate(),
this.bringtofront();
and this.TopMost = true;
None of them make any apparent difference at all.
I have research this problem extensively and this are the things everyone suggests and say work, but they don't work for me. Some have insinuated that I am violating all that is holy by trying to make my form topmost. However, I don't think very many people would like to open an application and have the main form for it show up behind everything else.
Any one have any other ideas about how to make sure my form is "in front", topmost, has focus?
When you do it this way, your application will have a brief moment where no window is available to receive the focus after the dialog closes. Windows is forced to find another window to give the focus to, that will be a window of another app. Your main window eventually appears, now behind that other's app window.
Display the dialog in an event handler of the Shown event instead. Or use the boilerplate File + Open command.
SOLUTION: this.Activate(); works but if called from the form Load event.
This will set the window on top:
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
private void Form1_Load(object sender, EventArgs e)
{
....
//after your code place the call to the function at the end.
SetForegroundWindow(this.Handle);
}
Althought as Mr. hans said and very well you are better off with another design.
If you can, move the ShowDialog out of the constructor, or try putting this in the constructor:
this.Shown += OnShown;
and move your ShowDialog to here:
private void OnShown(object sender, EventArgs eventArgs)
{
var result = new OpenFileDialog().ShowDialog();
}

Cannot access a disposed object

My program has multiple forms. The fifth and final form has a button that when clicked closes the application using the method Application.Exit(). However every time I click the button I receive the error 'cannot access a disposed object' surrounding this code on my first form:
frm2 f2 = new frm2();
this.Hide();
f2.ShowDialog();
this.Show();
The compiler indicates that the statement this.show() is the problem. Could someone explain why I am receiving this error and how to fix it?
Ok edited my answer, I reproduced your issue. If you want to use Form.ShowDialog then you should set the DialogResult of the control that is closing the application. So in the buttons properties you should set the dialog result to something, for example Cancel.
Then on the buttons click event you would do something like this:
private void btnClose_Click(object sender, EventArgs e)
{
if (this.DialogResult == DialogResult.Cancel)
{
Application.Exit();
}
}
Otherwise if you don't need to use Form.ShowDialog, you can just show Form2. The above does not produce the error in my testing.
In your code example, did frm2 make a call to Application.Exit? If it did, then why are you trying to call this.Show again?
Anyway, you may have a problem related to how you started the application's message loop. Are you running Application.Run(), or Application.Run(form1)?
If you provided a form to Application.Run() when you started your message loop, then you should not be calling Application.Exit in order to exit the application. Instead, you should simply close your main window, that would cause the message loop to finish, the call to Application.Run to return, and your application will terminate cleanly.

How to Make a Dialog Modal

I have a save file dialog set up to display but when I click off of it the dialog it disappears into the background without a tab or anything. My question is how do I make the dialog modal? If you don't know what I mean go into notepad hit save as and try to click off the dialog. You will see the window flashes and you get a nice sound informing you that you must do something in the dialog before doing anything else. I would like to achieve this effect with my dialog but I don't know how. I cannot simply use the Form.Modal property because that deals with forms and this isn't a Form. Could someone help me out here?
Thanks.
EDIT:
This is how I'm showing the dialog, it's running in XNA and when I click the save as button the EntrySelected() method is called:
private void EntrySelected(object sender, EventArgs e) {
if(sender == saveAsEntry) {
sfd = new SaveFileDialog();
thread = new Thread(ShowSaveDialog);
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
}
...
}
private void ShowSaveDialog() {
if(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
World.Save(sfd.FileName);
thread.Abort();
}
else {
thread.Abort();
}
}
Actualy your Dialog is a Form, As the above comment suggests there is not a Show method, you should be using ShowDialog() Command that opens it up as a Modal Dialog.
i.e.
SaveFileDialog1.ShowDialog();
Base on your edit, there is a version of ShowDialog where you assign the owner to the Dialog, maybe that will work for you.
SaveFileDialog1.ShowDialog(dialogOwner);
From above link:
This version of the ShowDialog method allows you to specify a specific form or control that will own the dialog box that is shown. If you use the version of this method that has no parameters, the dialog box being shown would be owned automatically by the currently active window of your application.

MDI application issues

General description of application:
Main form as MDI Container. On application start, if there is no xml file for database configuration (it is checked in Main form) Main form i call another form as showdialog() to fill all database info to build connection string. Then i close form and open another for login, then i get back to Main form, which has Split Container (2 panels: 1-menu on top, 2-content from child forms).
I open forms with:
private void PlanButton_Click(object sender, EventArgs e)
{
plan.TopLevel = false;
KontenerMenu.Panel2.Controls.Add(plan);
plan.Dock = DockStyle.Fill;
plan.Show();
}
and close form with:
private void Plan_FormClosing(object sender, FormClosingEventArgs e)
{
e.Cancel = false;
this.Hide();
}
Problems i have with app:
1. When i hit Cancel button when i open ShowDialog() form for database app crashes. Cancel button is simply:
private void cancelButton_Click(object sender, EventArgs e)
{
Application.Exit();
}
2. I have problem with clicking button to open/close/open again child forms. When i hit 'X' and want o open, app crashes with exception that it cannot refer to non-existing object
3. I have several buttons when i hit one and then another one it is always below the first one and not on the top
4. For example my form is 200x200 and in right down corner i have button (so location let's say 190x190) and i hit maximize button. My button is still on 190x190 and i would like to have it on down right corner. I couldn't find any property for that. Is there any or i have to write some code for that.
I'm not sure I understood your questions. Please make them clear.
But as an answer to question #4, there's an anchor property that does what you want.
Instead of trying to exit the application from within the dialog form itself you should return a DialogResult value and test that in the main form. The cancel button on the dialog doesn't need any code, just set its DialogResult property to 'Cancel' and if you have an Ok button set its DialogResult to 'OK'.
DialogForm f = new DialogForm();
DialogResult r = f.ShowDialog();
if (r == DialogResult.Cancel)
{
Close();
}
I can immediately see a number of problems with you code, including:
If you're going to add controls dynamically using Controls.Add, you should make sure the controls you're adding are dynamically created using new(). I get a sense that you don't have a clear understanding of object lifetimes and the WindowForms control life cycle.
The Application.Exit method should be used only in unusual cases. It's purpose is to achieve exactly the result you're observing - to immediately "crash" the application. The easiest way to have a button close a modal dialog is the set the DialogResult property of the button.
Winforms has a very elegant system for placement of control on a variable sized window. In order to use this system, you should familiarize yourself with the Anchor and Dock properties that are available on all controls.
It looks like what you're doing is attempting to learn WinForms by trial and error. You can do this, but it will take much longer and be much more painful that getting a hold of a good tutorial, book, or perhaps even attending a class if you can manage it. That will allow you to take these issues one at a time and have a much more enjoyable learning experience.

To close C# Forms Application

I have 2 forms ...when i start the application..and use the close "X" from the title bar the entire application closes...now when i select an option from the 1st form in my case it is a button "ADD" as its a phonebook application..it goes to the 2nd form as i have used 1stform.hide() and 2ndform.show()...now when i do "X" from the title bar it doesnt shutdown completely as the 1stform is not closed....how to program it in such a way tht any stage the entire application should close
Your first form is set as the startup form. That means whenever it gets closed, your entire application is closed. And conversely, your application does not close until it gets closed. So when you hide the startup form and show the second form, the user closing the second form does not trigger your application closing because they have only closed a secondary, non-modal dialog.
I recommend changing your design so that the startup form is also the main form of your application. No sense trying to work around built-in functionality that can actually be useful. You want the application to quit when the main form is closed, no matter what other child forms are opened.
But the quick-and-dirty solution in your case is to make a call to Application.Exit. That will close all of the currently open forms and quit your application immediately. As I said just above, I don't so much recommend this approach because having to call Application.Exit from every form's FormClosed event handler is a sign that something has gone seriously wrong in your design.
If the single startup form paradigm doesn't work out for you, you should look into taking matters into your own hands and customizing the Main method in your Program.cs source file. See the answers given to this related question for some ideas on how that might work for you.
What you can do is to use the Form's FormClosing event, and add the following code:
Application.Exit();
This will stop the entire application, and close all windows. However, if a background thread is running, the process itself will survive. In this case you can use:
Environment.Exit();
Add a Application.Exit on every forms's Closing event
like this:
Create an closing event handler first
private void Form_ClosingEventhandler()(object sender, CancelEventArgs e)
{
//Perform any processing if required like saving user settings or cleaning resources
Application.Exit();
}
then bind this event to any form you create.
//Where you create new form and show it.
Form1 frm= new Form1();
//set other properties
frm.Closing += new EventHandler(Form_ClosingEventhandler);
Form2 frm2= new Form2();
//set other properties
frm2.Closing += new EventHandler(Form_ClosingEventhandler);
Surely you don't want to shut down the entire application after the user adds a phone number? You just need to make sure that your main window becomes visible again. Write that like this:
private void AddButton_Click(object sender, EventArgs e) {
var frm = new AddPhoneNumber();
frm.StartPosition = FormStartPosition.Manual;
frm.Location = this.Location;
frm.Size = this.Size; // optional
frm.FormClosing += delegate { this.Show(); };
frm.Show();
this.Hide();
}

Categories