您的位置:首页 > 产品设计 > UI/UE

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

2014-04-04 21:46 337 查看
  越来越多的应用程序提供以命令行的方式来运行,通常的做法有两种:单独给应用程序写一个基于命令行运行的控制台程序,用户运行这个程序时它一定是以命令行的方式来运行;以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运行的参数来的会更直接些。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: