添加支持通过windows命令参数打开文件(文件路径作为参数)



我有一个工具只支持通过拖动或使用其"打开"按钮打开"*.TMC"文件。我将使该工具支持通过窗口命令参数(文件路径作为参数)打开文件,如

start""TMC多边形工具.exe"e:\tmcfile\kasumi.TMC"

这是源文件的链接http://www.mediafire.com/download/mc72m97h876i550/TMC.zip

这是"App.g.i.cs"的一部分(这是原始代码,有效但不接受通过命令参数打开)

[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main() {
    TMC_Tool.App app = new TMC_Tool.App();
    app.InitializeComponent();
    app.Run();
}

以及"MainWindow.xaml.cs"的一部分

public MainWindow()
{
    InitializeComponent();
    this.MouseLeftButtonDown += (sender, e) => this.DragMove();
    MainWindowTitle();
    changeLanguage();
    MessageWindow.lang(txt);
    ObjectSelectWindow.lang(txt);
    objSelWindow = new ObjectSelectWindow();
    Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;    
}

我试图添加字符串[]args,以使用现有的方法"OpenFile(args[0])",但它导致错误"Object reference not set to a instance of a Object"

这是我的代码(导致错误)"App.g.ics"

[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main(string[] args)
{
    TMC_Tool.App app = new TMC_Tool.App();
    app.InitializeComponent();
    app.Run(new MainWindow(args));
}

"MainWindow.xaml.cs"

public MainWindow(string[] args)
{
    InitializeComponent();
    if (args.Length > 0)
    {
        String FileEx = Path.GetExtension(args[0]).ToUpper();
        if (FileEx == ".TMC")
        OpenFile(args[0]);
    }
    this.MouseLeftButtonDown += (sender, e) => this.DragMove();
    MainWindowTitle();
    changeLanguage();
    MessageWindow.lang(txt);
    ObjectSelectWindow.lang(txt);
    objSelWindow = new ObjectSelectWindow();
    Application.Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
}

编辑:它现在有效,环境.GetCommandLineArgs()对非常有用

[System.STAThreadAttribute()]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public static void Main()
        {
            TMC_Tool.App app = new TMC_Tool.App();
            app.InitializeComponent();
            app.Run();
        }

public string filePath = null;
public MainWindow()
{
var args = Environment.GetCommandLineArgs();
// original code  .... 
filePath = args.Length > 1 ? args[1] : null;
        if (!string.IsNullOrEmpty(filePath))
        {
            OpenFile(filePath);
        }
}

感谢

只需将这一行添加到原始代码中即可。

public MainWindow()
{
    var args = Environment.GetCommandLineArgs();
    // path will be in args[1] if there is any.
}

最新更新