Display a form from the main form on startup - c#

I want to display a small form when the program is ran. This is the code:
private void Form1_Load(object sender, EventArgs e)
{
this.Opacity = 0;
InitForm init = new InitForm();
init.Show();
init.BringToFront();
comm = init.Start();
this.Opacity = 100;
}
The Start() method draws some lines to the list box on the InitForm.
I have two problems:
When the program starts, the list box is not populated, I just get
the waiting cursor, then the main form is displayed and the box is
populated at the same time;
The InitForm is behind the main form. How do I bring it to front?

Can't see a ListBox in that code. But painting doesn't happen until the UI thread goes idle again, after your Load event handler completes. Which also means that the Opacity assignment doesn't accomplish anything.
The Z-order problem is (partly) caused by this too, the main form isn't visible yet so BringToFront() doesn't work. Use either Show(this) so that InitForm is an owned window that always displays in front on the main form (recommended) or use the Shown event instead.

When the program starts, the list box is not populated, I just get the
waiting cursor, then the main form is displayed and the box is populated
at the same time;
What do you expect should happen? Your UI Thread is busy in executing the code below
this.Opacity = 0;
InitForm init = new InitForm();
init.Show();
init.BringToFront();
comm = init.Start();
this.Opacity = 100;
Once it gets freed it shows both the forms and list box populated. It is behaving correctly in my opinion
this.Opacity = 0;
Above line won't have any effect because UI thread will execute all the lines first then it will display the UI which means by the time UI shows something this.Opacity = 100; would have already been executed
I want to display a small form when the program is ran. The InitForm
is behind the main form. How do I bring it to front?
Why don't you set the Small Form as startup form and load the MainForm in load method of small form?

You should load the secondary form on a paralell thread.
So, on the Form1's load event handler you trigger the second thread, showing the Form2.

You can bring the Init form to front by setting this property
init.TopMost=true
It worked for me, check out,

Related

Button Click Event not updating textbox until Finished

Here's a C# code, What happens is when qsubmit button is clicked, program straight away displays "wait..!".
When I debug the program it is found that when I click and function executes textbox1.text = "Hello"; but doesn't updates textbox, it updates only when the control goes off the event function, when that happens value of textbox has already been changed to "wait..!". I want to know why it doesn't updates textbox instantly(If that would have done, I would have seen the text during Thread.Sleep())
private void Button_QSubmit_Click(object sender, EventArgs e)
{
textBox1.Text = "Hello";
Thread.Sleep(1000);
textBox1.Text = "Wait..!";
}
The UI thread is responsible to redraw the windows. So as long as you are doing this inside the UI Thread (e.g. a Button click event), the process is busy with your code and the window is not drawn.
A easy solution could be the use of an Timer. Just add an timer and in the button click you start it (e.g. you set itup to fire in 1 second).
The Timer Event then will simply set the Text.
https://msdn.microsoft.com/en-us/library/system.windows.forms.timer.aspx shows details about the Timer class.
You are hanging the UI Thread by calling Thread.Sleep from the Main Thread (UI), to update the text box you have to let the UI thread do its job outside your function to update the UI..anyway call Application.DoEvents() before the sleep. But calling Application.DoEvents() is a bad design

ShowDialog is just looping and creating new forms

Some info:
C#
Winforms project in visual studio 2012
.Net framework 4.5
Windows 8.1 OS x64
I am having the strangest bug!
Whenever i use:
private void Main_Load(object sender, EventArgs e)
{
TestForm form = new TestForm();
form.ShowDialog();
}
TestForm is just a stadard form with no controls added.
It will stop the main thread as it should! But instead of waiting for input, it will spawn a new "form" ever 0.5 sec aprox... i took a new solution and tried, and there it worked fine, but in the app im currently working on, it does this when ever it is run somewhere inside or from this form.
Placing the same form code inside a BackGroundWorker, then it works fine.
ONLY inside the main UI form i have, where this error occurs..
Using Show() works as normal, only 1 form opens, but does not work with dialog result :-/
I have no idea why and have never seen this before??
please help.
EDIT:
I did as Roy Dictus suggested, and placed a break point.
This is in my LauncherFrom that load Main:
private void timerHide_Tick(object sender, EventArgs e)
{
this.Hide();
// Open main form IF true else open hidden
var f = new a.Views.Main();
if (Properties.Settings.Default.StartHidden)
{
f.Opacity = 0;
f.Show();
f.Hide();
f.Opacity = 1;
}
else
{
f.Show();
}
// Stop timer
timerHide.Stop();
}
And it looks like timerHide.Stop(); is never being called.
I have used this many times before, and i have a few more ShowDialog() calls that work fine..
So why does this not work for only SOME of the ShowDialog();??
If i remove TestForm.ShowDialog(); from Main_Load() it calls timerHide.Stop(); just fine.
Your code never reaches tiemrHide.Stop(). That's because you show a modal dialog which runs its own message pump. And so your timer fires again and again.
Here's how it goes:
The timer event timerHide_Tick fires, and creates a new main form instance.
The new main form shows a modal dialog in Main_Load.
The modal dialog runs a message pump.
The timer event fires again.
Goto 1.
You need to call Stop() at the very start of timerHide_Tick.

How to show a WinForms Modal Dialog from a WPF App Thread

I have a WPF application. The main window of this application has a button. I am opening a WinForms modal dialog in a separate thread when this button is clicked. The trouble I am having is that the dialog does not behave like a modal i.e it is still possible to switch focus to the main window, whereas, I require to allow focus on the newly opened dialog and it should not be possible to select the main window.
Note: I cannot move the modalDialog.ShowDialog(); outside of the delegate because the dialog form creates controls dynamically and this means that these controls must remain on the thread that it was created. To be more clear, if I move the modalDialog.ShowDialog(); outside I will get an exception like so:
Cross-thread operation not vaild: Control 'DynamicList' accessed from a thread other than the one it was created on.
Any ideas as to how I might make the form behave as a modal?
Here is the code:
private void button1_Click(object sender, RoutedEventArgs e)
{
DoSomeAsyncWork();
}
private void DoSomeAsyncWork()
{
var modalDialog = new TestForm();
var backgroundThread = new Thread((
delegate()
{
// Call intensive method that creates dynamic controls
modalDialog.DoSomeLongWaitingCall();
modalDialog.ShowDialog();
}
));
backgroundThread.Start();
}
You should always create controls on the UI thread. If you do that, calling ShowDialog() through Dispatcher should work.

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

How to ensure a Windows Form is "fully" closed?

I have a form in a Windows form application that I want to display on top of a main form, close it, and then immediately show a dialog box using MessageBox.Show(). But the first form is still showing when the message box is shown, and it does not disappear until I click OK on the message box. I tried waiting to show the message box in an event handler for the form's VisibleChanged event and even calling Refresh() on both the form and the main form. Is there a way I can determine when the first form has fully disappeared before displaying the message box?
Edit:
Here is some code that demonstrates how the forms are being shown.
static class Program
{
// The main form is shown like this:
static void Main()
{
Application.Run(new MainForm());
}
}
public class Class1
{
// _modalForm is the first form that is displayed that won't fully go away
// when it is closed.
ModalForm _modalForm;
BackgroundWorker _worker;
public Class1()
{
_modalForm = new ModalForm();
_worker = new BackGroundWorker();
_worker.RunWorkerCompleted += backgroundWorker_RunWorkerCompleted
}
public void Method1()
{
_worker.RunWorkerAsync();
// The first form is shown.
_modalForm.ShowDialog();
}
// This code runs in the UI thread.
void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
_modalForm.VisibleChanged += new EventHandler(_modalForm_visibleChanged);
_modalForm.Close();
}
void _modalForm_visibleChanged(object sender, EventArgs e)
{
// When the message box is shown, the other form is still visible
// and remains so until I click OK.
MessageBox.Show("The other form was just closed.");
// Note: I originally tried to use the FormClosed event instead of
// VisibleChanged. Then I tried Deactivate, in attempt to use an event
// that occurred later thinking that might do the trick. VisibleChanged
// is the latest event that I found.
//
}
I'll guess that you are running your code on Windows XP or Vista/Win7 with Aero turned off. Closing a form does not make the pixels on the screen disappear instantly. The Windows window manager sees that the window for the form got destroyed and that this revealed parts of other windows underneath it. It will deliver a WM_PAINT message to let them know that they need to repaint the parts of the window that got revealed.
This will not work properly if one or more of those windows isn't actively pumping a message loop. They can't see the WM_PAINT message. They won't repaint themselves, the pixels of the closed form will remain on the screen.
Find out why these windows are not responding. Hopefully it is your window and the debugger can show you what the UI thread is doing. Make sure it isn't blocking on something or stuck in a loop.
After seeing the edit: there's indeed blocking going on, of a different kind. The MessageBox.Show() call is modal, it prevents the VisibleChanged event from completing. That delays the closing of the form.
Use System.Diagnostics.Debug.WriteLine() or Console.WriteLine() to get diagnostics in a Window Forms app. You'll see it in the Output window. Or simply use a debugger breakpoint.
The Form.FormClosed event is raised when the form completes closing. At this point, all Form.FormClosing event handlers have been run, and none of them canceled the close.
Form.FormClosed replaced Form.Closed (which is deprecated) in the .NET 2.0 framework.
Form.Closed Event
http://msdn.microsoft.com/en-us/library/system.windows.forms.form.closed(VS.71).aspx

Categories