1

I using following code to show OpenFileDialog using RoslynPad, it complied and run, but no dialog appear, so the snippet keep running forever:

#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);

What is correct way to make OpenFileDialog work with RoslynPad?

Environment:

  • OS: Windows 10 Pro 64 bit (2004)
  • RoslynPad: built from lastest master branch.
  • .NET Core: 3.1.402
Horizon
  • 81
  • 5
  • A dialog always requires an owner window, one it can stay on top of. There is [good evidence](https://github.com/aelij/RoslynPad/blob/master/src/RoslynPad.Avalonia/OpenFileDialogAdapter.cs) that is an unsubtle problem in this library. – Hans Passant Sep 28 '20 at 10:32
  • @HansPassant I think a dialog don't need an owner window in order to work. Checked with this piece of code in Visual Studio (.Net Core 3.1 with `true` config in project): `static void Main() { var fd = new OpenFileDialog(); var result = fd.ShowDialog(); Console.WriteLine(result); }`. – Horizon Sep 28 '20 at 10:55
  • The OpenFileDialog sometimes fails the first time you use the dialog. The default folder in VS may not be set correctly. I sometimes see this happen if you do not save project use File : SaveAll. Other times you need to set default folder before you use ShowDialog. – jdweng Sep 28 '20 at 11:00
  • @jdweng I'm able to make it work when run from Visual Studio. But in RoslynPad (a kind of lightweight editor), it doesn't work. – Horizon Sep 28 '20 at 11:03
  • The code is using Windows Dialogs not WinForm. See source at GitHub for Using Statement at top of module : https://github.com/aelij/RoslynPad/blob/master/src/RoslynPad/FolderBrowserDialogAdapter.cs – jdweng Sep 28 '20 at 11:10

1 Answers1

1

After checking the repo, I'm able to make OpenFileDialog work by adding below line:

await Helpers.RunWpfAsync();

The complete code is as below:

#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 creates a WPF Dispatcher thread and the code following the await runs under it. It will also work for Windows Forms.

Eli Arbel
  • 22,391
  • 3
  • 45
  • 71
Horizon
  • 81
  • 5