【问题标题】:How to start WPF based on Arguments如何根据参数启动 WPF
【发布时间】:2012-08-01 23:41:18
【问题描述】:

我目前正在开发一个执行某些文件操作的应用程序,我希望能够通过控制台或 UI 进行操作(我选择了 WPF)。

我很想说:(伪)

if ( Environment.GetCommandLineArgs().Length > 0 )
{
    //Do not Open WPF UI, Instead do manipulate based
    //on the arguments passed in
}
else
{
    //Open the WPF UI
}

我已经阅读了一些以编程方式启动 WPF 窗口/应用程序的不同方法,例如:

Application app = new Application ();
app.Run(new Window1());

但我不完全确定我只想将其插入控制台应用程序。

是否有人对我如何实现这一目标提出了最佳做法或建议?主要的处理功能在我创建的一个 Helper 类中。所以基本上我要么想要一个静态启动方法(如标准控制台应用程序创建)或 UI 来访问 Helper 类,具体取决于传入的参数。

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    Application 类中有一个事件“StartUp”你可以使用它。它为您提供您通过命令提示符提供的参数。以下是来自MSDN 的示例:

    App.xaml

    <Application x:Class="WpfApplication99.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="App_Startup">
    </Application>
    

    App.xaml.cs

    public partial class App : Application
    {
        void App_Startup(object sender, StartupEventArgs e)
        {
            // Application is running
            // Process command line args
            bool startMinimized = false;
            for (int i = 0; i != e.Args.Length; ++i)
            {
                if (e.Args[i] == "/StartMinimized")
                {
                    startMinimized = true;
                }
            }
    
            // Create main application window, starting minimized if specified
            MainWindow mainWindow = new MainWindow();
            if (startMinimized)
            {
                mainWindow.WindowState = WindowState.Minimized;
            }
            mainWindow.Show();
        }
    }
    

    我希望这会有所帮助。

    【讨论】:

    • 这是正确的做法。见msdn.microsoft.com/en-us/library/…
    • 除了上面的建议之外,我相信值得注意的是,如果App.xaml中的StartupUri属性存在,则需要将其移除。如果不这样做,您将生成两个窗口实例。
    【解决方案2】:

    有 2 个选项可以获取命令行参数
    1)如果您想阅读参数OnStartup。这有利于args 的全局访问。

    App.xaml.cs 中覆盖OnStartup 并查看StartupEventArgs 类的Args 属性。

    public partial class App : Application
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            foreach (string arg in e.Args)
            {
                // TODO: whatever
            }
            base.OnStartup(e);
        }
    }
    

    2) 另一种简单的方法是从环境对象中读取参数。

    Environment.GetCommandLineArgs();

    这可以在应用程序的任何地方使用,例如从表单/页面也可以。

    【讨论】:

    • App_Startup 的 StartupEventArgs.Args 更好。 Environment.GetCommandLineArgs 的问题在于它可能包含一些垃圾,例如从 Visual Studio 运行 WPF 项目时的“.vhost.exe”。
    猜你喜欢
    • 2017-10-09
    • 2020-09-21
    • 1970-01-01
    • 2015-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多