-->

Sunday, June 2, 2013

How to open a new form and close an existing in c# Windows Forms

As we all know that we don’t want unauthorized users to let them access our programs, so the better approach is to use a login form and then run our main application. For that simple task we have to close our first thread in which login form is running and start a new thread in which our new form will open.

To start a new thread Microsoft provides a class i.e. System.Threading.Thread
In Visual Studio 2012 In which some function have written to play with threads like, Start(), Abort() etc.


First create a new form named login and set this our default form through program.cs, now in login form designer window create a new button having text “Start New thread”. Generate click event of this button and write following set of lines:

start new thread after closing main thread
Here appThread is a variable of type System.Threading.Thread class and LaunchAdminApplication is a function that have work to do now.

In above code, first we have called the constructor of Thread class that needs a parameter, which is name of function, having the work to do. At the last we call Start() function which causes the operating system to change the state of current instance.


run new application
Application.Run() is the same function our program.cs class have which is used to define which form is going to be shown.

So finally Form1 will be the new instance of this windows form application.

Download Example Here.
© Copyright 2013 Computer Programming | All Right Reserved