Opening a new form via label causes Error to appear - c#

I'm trying to make a new form appear when I click on a label. I'm using Windows Application Forms.
Here's the code:
private void label1_Click(object sender, EventArgs e)
{
Form parpokeru = new Form();
parpokeru.Show();
parpokeru.ShowDialog();
}
When I click on the label, a error appears (Unhandled exception has occurred in your application...). Can anyone tell me how to fix it?

Call .Show() or .ShowDialog(). Not both.
Show() will display your second form, while still allowing the user to access the first form.
ShowDialog() will display your second form as "modal". Execution of code in the first form stops while the second form is open (at least on the main thread.. for example, timers will continue to run), and the user will not be able to access your first form while the second is open.

When you call the Show method your form is shown on video like another window and the code returns immediately from the call. So your code continues and all the forms of your application are available for the user interaction. It is calledd a modeless dialog
On the contrary, ShowDialog is a blocking call. The code doesn't return from this call until something happen inside the called form that terminates the visualization of the form. As an example comes to ming a call to the methid Hide or a click on a button with its DialogResult property set to something different from DialogResult.None. At this point the code from ShowDialog returns and the normal processing continue. While the code is blocked inside the ShowDialog the application is blocked and the user cannot interact with other forms or menus or whatever is displayed on video. It is called modal dialog
Another difference is ShowDialog returns value (a DialogResult enum value) that can can be used to determine how the user closed the form (DialogResult.Cancel, DialogResult.OK), also ShowDialog does not call the Dispose method at closing time. This will allow to retrieve property from the Modal Dialog like user inputs for further processing.
I cannot imagine what happen in the internal processing of your form if, after a modeless call to Show you call immediately a ShowDialog on the same form instance. However, an exception is really the minimum to expect from this code.

Related

c# How to allow some lower level forms to be acessible despite active form called by ShowDialog() method?

i got application, it shows 3 forms: log window, status window, and option window, option window calls some other forms and some of these forms are required to be called using ShowDialog() to return dialog result value for further decision making.
Using ShowDialog() raises problem, cause form called by that method excluding other forms from being accessible.
So my problem is i would like to be able to make atleast log window accessible no matter how much other forms has been called. Is there a way to make log window to independent form other forms, or could it be taken over by form called as last?
EDIT:
I failed to mention that the behaviour provided by ShowDialog() is quite usefull in my app and that i only lack ability to free that one or two forms from being locked. Switching to Show() is not option I'm considering as best while other forms, that are parent to form called by ShowDialog() are required to be still locked.
You'll have to make a choice between the two.
Use ShowDialog(), so that your parent form pauses execution, and only resumes when the second form is closed, or
Use Show(), so that your parent form continues execution after displaying the second form.
If you want to take some action, or read values from the second form when it's closed, then subscribe to its Closed event before you show it.
Let's assume your second form has a "First Name" TextBox, and a property to return that value:
public string FirstName
{
get { return yourFirstNameTextBox.Text; }
}
In your first form, you can subscribe to an event to take some action when the event occurs, like this:
var f2 = new SecondForm();
f2.Closed += (s, e) => MessageBox.Show(f2.FirstName);
f2.Show();
Now the user can continue on their way with both forms, and when the second form is closed, a message box will display the value of the "First Name" TextBox.
You'll probably want to do something more meaningful than this. Instead of displaying a message box, you could update a field on the first form, or take some any other action or set of actions that you want.
f2.Closed += (s, e) =>
{
MessageBox.Show(f2.FirstName);
nameLabel.Text = f2.FirstName;
// another action
// yet another action
};
So I now modeled your situation and found solution:
Use Show() instead ShowDialog() for dialog.
Write some code in the dialog to close it window after press the button (Ok, Cancel etc.). Because auto-closing works with ShowDialog only. But you don't need to set DialogResult manually.
At the Options form subscribe to FormClosed event to get DialogResult. For example:
dlg.FormClosed += (o, a) => { this.Text = dlg.DialogResult.ToString(); };
Handle Activate event of Options form to prevent focusing on parent window when dialog is opened:
if (dlg != null) dlg.Focus();
This solution has some difference with system behaviour of ShowDialog, but it works good.

Form in C# returns DialogResult.Cancel to Parent When It is Minimized

I have a form "Main" and in Main I am creating another form which I use .ShowDialog() to display it. I do this because I don't want the rest of the code to in Main to execute until after the new form is completed. I am allowing a user to minimize the new form to system tray.
The problem: When the form gets minimized it is returning DialogResult.Cancel to the Main form that called it, causing the next line to run early.
Code to create form from Main form:
for(int i = 0; i < lvAll.SelectedItems.Count; i++)
{
this.Hide();
this.run = new RunProfile(this.profiles[lvAll.SelectedItems[i].Text]);
DialogResult result = run.ShowDialog();
MessageBox.Show(result.ToString());
}
In the new form a user will get a list of files that copy... now the user can continue and copy those files and I would expect to return a result of OK and if not I assume they are going to cancel and return Cancel...
Is my only recourse to return Abort from the new form if a user specifies a cancel and assume that a cancel is someone trying to minimize? This just seems odd
You could handle this in a number of ways, one way is like what follows:
MainTestForm mainTestForm = new MainTestForm();
if (mainTestForm.ShowDialog() != System.Windows.Forms.DialogResult.OK)
{
return;
}
You must set the DialogResult state when you close the form like
this.DialogResult = System.Windows.Forms.DialogResult.OK;
I hope this helps.
This is entirely by design. When you hide a modal dialog, the user doesn't have any way to get back to the program. Dialogs don't have a taskbar button and the rest of the windows in the app are disabled so cannot be activated. The only recourse the user would have is to kill your program with Task Manager.
So Winforms does the logical thing, it automatically closes the dialog to avoid this UI trap. And of course you'll get DialogResult.Cancel.
Use proper UI design, a dialog should always have its MinimizeBox property set to False.
I'm not sure what you are trying to achieve with that. However, to get the Dialog to return anything else, you have to set it in the form's (Dialog's) DialogResult property before the form is closed.
You may also use the Form_Closing event of the dialog to set the DialogResult property to what you want. This is done before the form closes.
Here is a quote from MSDN regarding ShowDialog:
When this method is called, the code following it is not executed
until after the dialog box is closed.
After further reading it does state the X does not close the form but hides it and so you must dispose of it:
When a form is displayed as a modal dialog box, clicking the Close
button (the button with an X in the top-right corner of the form)
causes the form to be hidden and the DialogResult property to be set
to DialogResult.Cancel. The Close method is not automatically called
when the user clicks the Close button of a dialog box or sets the
value of the DialogResult property. Instead, the form is hidden and
can be shown again without creating a new instance of the dialog box.
Because of this behavior, you must call the Dispose method of the form
when the form is no longer needed by your application.
It seems this same issues applies to minimizing a userform as well.

How do I cleanly pause a thread until another thread completes or a value is changed

Using C#: I have a class "MsgBox", a special Message Box formatted to my application. It runs on an instance, the point was so that when I called: 'new MsgBox("Message Text");' it would pause the calling thread until the form gets a response/closes or whatever. I tried running the Form on another thread and using Thread.Suspend()/Resume() and it freezes the whole computer for a two or three seconds, then works fine. Same with Thread.Join(). Is there a more efficient way to hold the thread?
You can use Form.ShowDialog method to display a modal dialog box in your application. When this method is called, the code following it is not executed until after the dialog box is closed.
The dialog box can be assigned one of the values of the DialogResult enumeration by assigning it to the DialogResult property of a Button on the form or by setting the DialogResult property of the form in code. This value is then returned by this method. You can use this return value to determine how to process the actions that occurred in the dialog box. For example, if the dialog box was closed and returned the DialogResult.Cancel value through this method, you could prevent code following the call to ShowDialog from executing.

What's the difference between Application.Run() and Form.ShowDialog()?

In my application I want to show a login form first and then the main form if the login has been successful. Currently I'm doing it something like this:
var A = new LoginForm();
if ( A.ShowDialog() == DialogResult.OK )
Application.Run(new MainForm());
But then I started wondering - what's the point of the Application.Run()? Why not just do (new MainForm()).ShowDialog() as well? What's the difference? And what would be the correct way to achieve what I want?
Application.Run(Form) starts a message loop on the current thread and displays the specified form. The message loop enables the form to receive Windows messages (eg, key presses, mouse clicks, paint invalidations) to allow it to appear responsive and have interaction with the user. When you call ShowDialog() on a Form instance, it actually does a similar thing and creates a modal message loop for the form on which ShowDialog has been called.
There is not much difference between the two calls. Application.Run does add some extra event handling enabling you to do some tidying up of resources when the main form is closed (see Application.ThreadExit).
The recommended way to start WinForms applications is using Application.Run, but I suspect this is more of a convention than a rule. The biggest reason to use Application.Run is if you want to open multiple non-modal forms. You can do this using:
new Form().Show();
new Form().Show();
Application.Run();
You could not achieve this using the ShowDialog() method as one of the forms would have to be modal.
As for your question of how to show a login form and then the main form if the login is successful, I think what you have is fine:
if (new LoginForm().ShowDialog() == DialogResult.OK)
{
Application.Run(new MainForm());
}
The alternative is to do the plumbing yourself and open an instance of MainForm in the closing event of the LoginForm if the login was successful.
From MSDN:
This method adds an event handler to
the mainForm parameter for the Closed
event. The event handler calls
ExitThread to clean up the
application.
http://msdn.microsoft.com/en-us/library/ms157902.aspx
From my testing, I noticed this main difference:
When Application.Run is used, the form's Close button (red X) returns DialogResult.None; however, when ShowDialog is used, the Close button produces DialogResult.Cancel.
Does this matter to you? In my code, I was testing for DialogResult.Cancel to determine the exit code of my application. That was broken when the red X was used to close the form. I now test for DialogResult.OK to indicate a successful exit.
return myForm.DialogResult == DialogResult.OK ? 0 : 1;
One key difference is that ShowDialog is usually a modal Dialog. If you wanted to create a user-friendly toolset, you would not want it to be comprised of modal dialog boxes.
Also, Application.Run() accepts more than just a form. It has a few overloads.
As for your application, I do not think it matters much. Application.Run makes sense to me because it denotes the start of your actual Application.
The documentation of the overload
public static void Run(
ApplicationContext context );
has a neat example with a different approach that involves two forms as well.
For a more concerete example of a difference:
If your main form is an MDI form, then the behavior on clicking the close button (the 'x' in the upper right, or Alt-F4) is different depending on which method you use to show the form.
With Application.Run(mainForm), the closing event of the child forms run, then the main form's closing event runs.
With mainForm.ShowDialog, the closing event of the main form runs, and the closing event of the child forms do not run.
Application.Run() is for the start of application while MainForm is part of the application and MainForm()).ShowDialog() used to display it only.
Application.Run() is the entry point for your Application. same as Main() method is for some class or ApplicationStart() for a WebApplication
Application.Run() has different overloads, one of which is without parameters. That Method starts application without an initial form.
From my testing I notice that using Application.Run buttons with DialogResult does not close the form (OnFormClosing is not hit) compare to ShowDialog in which the buttons with DialogResult hit OnFormClosing and the close the form.

Calling a C# asynchronus method from a VB6 application

I have a C# dll that when the main method is called, it opens a windows form. This dll is currently accessed through VBA by a vendor application. The problem is that when the dll is called and the form opens, the user loses the ability to interact with the vendor application. I was hoping that if I could modify the dll to support an asynchronus call, then the control could be returned to the calling application to allow the user to turn pages, zoom in or out, etc. Then once the user completes the pop-up form we could have a callback or something to return the information to the vba app customizations.
Rather than making the async call from VB, it would be far easier to modify the C# code to open the window asynchronously, and then return.
You could do this just by changing the line that opens the window from .ShowDialog() to .Show().
Obviously, this may not be an option if you don't have access to the C# dll's code, but I thought I would suggest it.
If you do decide to change to use Show() instead of ShowDialog() you may have to handle your dialog result differently.
You're new code will look something like this:
MyForm win = new MyForm();
win.Show();
A non modal dialog doesn't block the calling code, so your calling code will continue without waiting for a result.
The simplest way to handle this would be to attach an event handler to the form's .OnClosed event. This will then be triggered when the user closes the form.
MyForm win = new MyForm();
win.OnClosed += new EventHandler<FormClosedEventArgs>(YourEventHandlerMethod)
win.Show();
You can add a public boolean property to the form (with a private setter) that you set internally when the ok/cancel buttons are pressed (Along with calling the close method). You can then check this property after the form has closed from within your on closed handler. (The sender property will be your reference to the form, you'll just have to cast it to the correct type first).
So your event handler method will look like this:
private void EventHandler<FormClosedEventArgs> YourEventHandlerMethod(Object sender, FormClosedEventArgs e)
{
MyForm f = (MyForm)sender;
bool result = f.TheResultProperty;
// Now do your callback.
}
Finally, now you have some code that runs after the form closes, and has access to the forms result, you just need to let your VBA code know it's ready - I'll leave this up to you.

Categories