Saturday 22 August 2015

How to run a Windows Form from a console application in C#?

There are many way to do it, but its totally depends upon your requirement.

  • Attached within process
  • Independent Calling

Attached within process


If you want to take input from form textbox then you need to use ShowDialog()

Program.cs

using System.Windows.Forms;
 class Program
    {
        public static string tokenpassword = "";

        static void Main(string[] args)
        {

            LoginTokenForm f = new LoginTokenForm();
            f.ShowDialog();

            Console.WriteLine("tokenpassword:" +  tokenpassword);
            Console.Read();
        }
       
    }


or 

class Program
    {
        public static string tokenpassword = "";

        static void Main(string[] args)
        {
            openlogin();

            Console.WriteLine("tokenpassword:" +  tokenpassword);
            Console.Read();
        }


        [STAThread] //optional
        static bool openlogin()
        {
            Application.Run(new LoginTokenForm());
            return true;
        }
    }



LoginTokenForm.cs
private void button1_Click(object sender, EventArgs e)
        {
            Program.tokenpassword = textBox1.Text;
            this.Close();
        }

Output:
tokenpassword:123456

Independent Calling

You need to run application in independent thread, like

Program.cs
using System.Threading.Tasks;
using System.Windows.Forms;
 class Program
    {
        public static string tokenpassword = "";

        static void Main(string[] args)
        {

            Task<bool> chunkUpdate = new Task<bool>(() => openlogin());
            chunkUpdate.Start();

            Console.WriteLine("tokenpassword:" +  tokenpassword);
            Console.Read();
        }


        
        static bool openlogin()
        {
            Application.Run(new LoginTokenForm());
            return true;
        }
    }

Output
tokenpassword: