如何判断应用程序运行于GUI模式还是命令行

  越来越多的应用程序提供以命令行的方式来运行,通常的做法有两种:单独给应用程序写一个基于命令行运行的控制台程序,用户运行这个程序时它一定是以命令行的方式来运行;以GUI和Command Line共享一个应用或exe文件,但通过不同的arguments来判断,最终分别做不同的处理。

  对于单独给应用程序写基于命令行运行的控制台程序,无非是通过判断传递的args数组来辨别并设置程序运行所需要的参数,最终设定各项参数而完成所需要的工作。在这里建议提供对于/?的帮助菜单,方便用户查询。

  if (args.Length != 1)

  {

  Console.WriteLine("ERROR: Invalid Argument.");

  Console.WriteLine(@"Type 'MyConsole.exe /?' for usage.");

  return false;

  }

  else

  {

  if (args[0] == @"/?")

  {

  Console.WriteLine("The syntax for this program is:");

  Console.WriteLine("MyConsole.exe [project file]");

  Console.WriteLine();

  Console.WriteLine("[project file] The path to the XML project file.");

  return false;

  }

  else

  {

  string strFilePath = args[0];

  if (File.Exists(strFilePath))

  {

  ……

  return true;

  }

  else

  {

  Console.WriteLine("Can not find the specified project file:'" + args[0] + "'");

  Console.WriteLine("Please check the path of project file and try again.");

  return false;

  }

  }

  }

  在调试这样的程序时可以通过给项目属性中设置参数来调试,这样设置的参数在项目启动时会以参数的形式传入。

  对于一套程序入口却分别接受GUI调用和Command Line方式运行,我们就必须判断当前是以什么方式来运行程序的,检测当前的运行宿主环境就可以帮助我们来判断出到底是否是运行在Console模式下。通过检测程序运行的进程我们可以判断出它的运行方式。

  [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);

  IntPtr ptr = GetForegroundWindow();

  int processId;

  GetWindowThreadProcessId(ptr, out processId);

  Process process = Process.GetProcessById(processId);

  if (process.ProcessName == "cmd")

  {

  http://gdjs.info

  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运行的参数来的会更直接些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值