IntPtr ptr = GetForegroundWindow();
int processId;
GetWindowThreadProcessId(ptr, out processId);
Process process = Process.GetProcessById(processId);
if (process.ProcessName == "cmd")
{
AttachConsole(process.Id);
Console.WriteLine("start from command line");
//return false;
//isStartFromCommandLine = true;
//TODO: Hide the GUI and perform the actions.
//Release the console.
FreeConsole();
return;
}
//GUI mode
Page01StartUp form = new Page01StartUp();
form.Show();
form.Focus();
form.BringToFront();
Application.Run();
在这个Case中,程序除了以正常的GUI方式运行外就是命令行方式运行,所以只区别判断了命令行方式,其余时候正常的以GUI方式运行即可。
还有一种方式是这个程序可以在命令行方式里通过不同的参数来启动GUI模式运行,Console模式运行等。通过添加一个来表示是以GUI还是console运行的参数来的会更直接些。
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FreeConsole();
[DllImport("kernel32", SetLastError = true)]
static extern bool AttachConsole(int dwProcessId);
[DllImport("user32.dll")]
static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll", SetLastError = true)]
static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);
static void Main(string args)
{
string mode = args.Length > 0 ? args[0] : "gui"; //default to gui
if (mode == "gui")
{
MessageBox.