Windows Form Pass an Argument from Outside and Attach to Debugger

In this blog you will learn passing an argument from outside the application and attach the debugger to a process.

I know that some of the windows form developers may be using this feature already but most of the windows form developer is not aware about it and they use to write Thread.Sleep(time); and rebuild the program and then attach to process.
 
Suppose we have to attach a debugger then:
  • Go to Main method and Write Thread.Sleep(time).
  • Build the solution (also need to copy data to another server if it is running on Remote server).
  • Attach to process .
If you have given very less time e.g. 20 seconds and do remote debugging. It might be possible that the time expires and till that you are not able to attach the debugger. And if you provide long time e.g. 3 minutes then you have to wait for 3 minutes even though you are managed to attach debugger in 30 seconds. 
  • Before sending to client you need to remove Thread.Sleep(time); because it will force to sleep the application on live server.
  • When you are using TFS/SVN as version Control in that case you may need to revert your code Thread.Sleep(time); before taking latest.
Solution of all these issues is very simple by passing the argument to main method. Let see the step-wise process how to pass argument to main method.
  1. Create a windows form application or use your existing windows form application.
  2. Go Main Method.
  3. Modify your Main Method.
  1. static void Main()  
  2.    {  
  3.       //do something  
  4.    } 
 To
  1. static void Main(string[] args)  
  2.   {  
  3.    if (args.Length>0)  
  4.    {  
  5.     if (args[0]=="wait")  
  6.     {                           MessageBox.Show("Please attach a debugger if you want to debug the application otherwise click ok to continue");  
  7.      }  
  8.                  
  9.     }  
  10.          //do something  
  11.    } 
Build you application and go to bin directory and create a shortcut of your main exe file.

Select the shortcut file --> right click on it --> properties --> Select Shortcut Tab --> on Taget TextBox.
If path is “…\Debug\WindowsFormsApplication1.exe” change it to “…\Debug\WindowsFormsApplication1.exe wait”.

Now whenever you want to debug the application run the shortcut file and if you do not want to debug it run the main file.

The above changes are one time changes and it’s for lifetime. You can check-in it to you versioning control TFS/SVN. Create and build the application you can send the delivery to customer without making any changes and from next time have not to do anything just click on shortcut to debug it.