官术网_书友最值得收藏!

1.4 輸入參數

在WinForm應用程序中,應用程序的入口函數是一個Main方法,我們可以向該方法傳遞一個命令行參數。WPF也可以用類似的方法,而且更加靈活。

方法1:在Application類中定義帶參數的Main方法,如下面的DesktopApp:

  namespace Yingbao.Chapter1.WpfAppWithInputParam
  {
      public class DesktopApp: Application
      {
        [STAThread]
        public static void Main(string[] command )
        {
        //...加入你的程序
        }
      }
  }

方法2:調用GetCommandLineArgs,如下面的Main中所用的方法:

  namespace Yingbao.Chapter1.WpfAppWithInputParam
  {
      public class DesktopApp: Application
      {
        [STAThread]
        public static void Main( )
        {
          string[] commandline = Environment.GetCommandLineArgs();
          foreach (string cmd in commandline)
          {
            Console.Write(cmd);
          }
        }
      }
  }

方法3:移植OnStartUp方法

方法1和方法2都需要處理入口函數Main。我們在Visual Studio中創建WPF應用程序,通常使用項目模板,該項目模板創建的Application類由兩部分組成,一部分是XAML,一部分是后臺C#。WPF在編譯時,會自動產生一個Main函數,即在這種情況下,我們不能定義自己的Main方法。這時候若要處理命令行參數,則要移植OnStartUp方法:

  namespace Yingbao.Chapter1.WPFStartUp
  {
      public partial class App : Application
      {
        protected override void OnStartup(StartupEventArgs e)
        {
          base.OnStartup(e);
          string[] commands = e.Args;
          foreach (string command in commands)
          {
            Console.Write(command);
          }
          //你自己的邏輯
        }
      }
  }
主站蜘蛛池模板: 巫山县| 琼结县| 聂拉木县| 庆云县| 鄄城县| 沙湾县| 永兴县| 昌平区| 莱阳市| 姚安县| 平凉市| 抚松县| 乃东县| 和平县| 惠水县| 吴堡县| 金秀| 台东市| 聂荣县| 大英县| 锡林浩特市| 宿松县| 绥中县| 石首市| 白沙| 古浪县| 柳江县| 洞头县| 榆林市| 本溪市| 水富县| 将乐县| 会泽县| 沙河市| 德州市| 招远市| 文成县| 洛南县| 阿坝县| 彭水| 东辽县|