Software design and other ramblings RSS 2.0
# Wednesday, 02 July 2008

The other day I had to update a existing windows GUI application to enable it to be called via the command line. In order to do this, you need to add the following import to your .NET application (C# example shown):

/// <summary>
/// AttachConsole gives the ability for a GUI application to write to the console window of the console from which it was started.
/// </summary>
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
static extern bool AttachConsole(uint dwProcessId);

/// <summary>
/// Flag indicating that we should attach to parent console
/// </summary>
const uint ATTACH_PARENT_PROCESS = 0x0ffffffff;

After adding these declarations to your main class, its a simple case of adapting your Main method to detect if you're running in console or GUI mode and acting accordingly. E.g:

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
     // Are we in console mode
     bool isConsole = args.Length > 0;

     if (!isConsole)
     {
          RunVisual();
     }
     else
     {
          // Attach to console
          AttachConsole(ATTACH_PARENT_PROCESS);

          // Run console app
          RunConsole(args);
     }
}
Wednesday, 02 July 2008 16:31:56 (GMT Daylight Time, UTC+01:00)  #    Comments [0] -
.NET | C# | Software Development
Top Cashback
TopCashback
Archive
<2017 December>
SunMonTueWedThuFriSat
262728293012
3456789
10111213141516
17181920212223
24252627282930
31123456
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2017 Scott Hill

Sign In
Statistics
Total Posts: 8
This Year: 0
This Month: 0
This Week: 0
Comments: 2
All Content © 2017, Scott Hill