【问题标题】:How to show OpenFileDialog in RoslynPad如何在 RoslynPad 中显示 OpenFileDialog
【发布时间】:2020-09-28 10:11:12
【问题描述】:

我使用以下代码显示OpenFileDialog 使用RoslynPad,它编译并运行,但没有出现对话框,所以 sn-p 一直运行:

#r "framework:Microsoft.WindowsDesktop.App"

using System.Windows.Forms;

var fd = new OpenFileDialog
{
    Filter = "Solution files (*.sln)|*.sln"
};

if (fd.ShowDialog() == DialogResult.OK)
    Console.WriteLine(fd.FileName);

OpenFileDialog 与 RoslynPad 一起使用的正确方法是什么?

环境:

  • 操作系统:Windows 10 Pro 64 位 (2004)
  • RoslynPad:由最新的 master 分支构建。
  • .NET Core:3.1.402

【问题讨论】:

  • 一个对话框总是需要一个所有者窗口,它可以留在上面。在这个库中有good evidence 是一个不明显的问题。
  • @HansPassant 我认为对话框不需要所有者窗口即可工作。在 Visual Studio 中检查了这段代码(.Net Core 3.1,项目中有<UseWindowsForms>true</UseWindowsForms> 配置):static void Main() { var fd = new OpenFileDialog(); var result = fd.ShowDialog(); Console.WriteLine(result); }
  • 第一次使用对话框时,OpenFileDialog 有时会失败。 VS中的默认文件夹可能设置不正确。如果您不使用 File : SaveAll 保存项目,我有时会看到这种情况。其他时候你需要在使用 ShowDialog 之前设置默认文件夹。
  • @jdweng 我可以在从 Visual Studio 运行时使其工作。但在 RoslynPad(一种轻量级编辑器)中,它不起作用。
  • 代码使用的是 Windows 对话框而不是 WinForm。有关模块顶部的 Using 语句,请参见 GitHub 上的源代码:github.com/aelij/RoslynPad/blob/master/src/RoslynPad/…

标签: c# openfiledialog .net-core-3.1 roslynpad


【解决方案1】:

检查 repo 后,我可以通过添加以下行使 OpenFileDialog 工作:

await Helpers.RunWpfAsync();

完整代码如下:

#r "framework:Microsoft.WindowsDesktop.App"

using Microsoft.Win32;

await Helpers.RunWpfAsync(); // initializes a dispatcher thread

var fd = new OpenFileDialog
{
    Filter = "Solution files (*.sln)|*.sln"
};

if (fd.ShowDialog() == true)
    Console.WriteLine(fd.FileName);

不确定这是否是最好的方法,但它有效!

【讨论】:

  • 是的,这是正确的做法 :) RunWpfAsync 基本上创建了一个 WPF Dispatcher 并遵循 await,运行它下的所有内容。它也适用于 Windows 窗体。
  • @EliArbel 感谢您提供了一个很棒的开源项目。对我帮助很大!
猜你喜欢
  • 2012-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 2012-11-07
  • 2016-09-03
  • 1970-01-01
相关资源
最近更新 更多