【问题标题】:C# Winforms application opens from Command Prompt and in debugger, but not from File ExplorerC# Winforms 应用程序从命令提示符和调试器中打开,但不是从文件资源管理器中打开
【发布时间】:2018-11-28 04:26:44
【问题描述】:

我对这个 C# Winforms 应用程序进行了编程,以在文件资源管理器中单击文件时打开(通过“打开方式...”命令)。但是,该应用程序没有打开,而是直接崩溃而没有错误消息。在任务管理器中,可以看到应用在消失之前短暂运行。

从测试应用程序中,我发现文件资源管理器发送文件路径作为第一个参数。从调试器或命令提示符启动应用程序有效(即使使用文件路径作为参数)。

代码如下:

public static void Main(string[] args) {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        MainForm form = new MainForm();

        if (args.Length > 0) {
            if (System.IO.File.Exists(args[0])) {
                form.OpenFile_(args[0]);
            }
        }

        try {
            Application.Run(form);
        } catch (Exception e) {
            form = new MainForm();
            form.SetStatus("Something went wrong opening the file.");
            Application.Run(form);
        }
    }

即使使用 try/catch 块,应用程序也无法从文件资源管理器启动。 它在命令提示符或调试器中没有任何问题。

【问题讨论】:

  • System.Diagnostics.Debugger.Launch() 在 Main 方法的第一行并从 Open with 启动您的应用程序。还要检查事件查看器是否有异常。
  • 运行eventvwr.msc 并查看应用程序事件;你可能会发现导致你的程序死在那里的异常。
  • 您还应该将事件处理程序附加到Application.ThreadExceptionAppDomain.CurrentDomain.UnhandledException 事件以显示带有异常详细信息的消息框。您也可以根据我们的需要使用Application.SetUnhandledExceptionMode方法。
  • 我使用类似:(Program.cs)if (args.Length > 0) { Application.Run(new MyMainForm(args)); } else { Application.Run(new MyMainForm()); }。在起始表单中:public MyMainForm() : this(null) { }public MyMainForm(string[] args) { //Processing }。在注册表中,HKEY_CLASSES_ROOT,在文件扩展名部分 (.something),(默认)REG_SZ "MyAppID.Version"。在MyAppID.Version:(默认)REG_SZ [文件类型描述],shell/open/command "[Path]\executable.exe" -open "%1" %*。所有错误处理都在MyMainForm 中执行,同时检查args[] 内容。
  • 该尝试放置不正确,它无法捕获 MainForm.OpenFile() 失败。事实上,它根本无法捕获任何东西,似乎只有在您使用调试器时才会捕获。为 AppDomain.CurrentDomain.UnhandledException 编写事件处理程序从来都不是可选的。

标签: c# .net winforms


【解决方案1】:

真的很简单:

代替:

string SettingsFilePath = "settings.txt";

用途:

string SettingsFilePath = Application.StartupPath + "\\settings.txt";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多