Search code examples
c#.netwinapidllimportopenfiledialog

`tinyfd_selectFolderDialogW()` doesn't work from C# app


I have a cross-platform C# (.NET) application that uses a "tinyfiledialogs" library.

tinyfd_openFileDialogW() (and tinyfd_openFileDialog()) works as expected, but tinyfd_selectFolderDialogW() doesn't:

  1. The dialog doesn't allow me to actually select a folder - the "OK" button is deactivated.
  2. It sometimes doesn't open at all - the application freezes.

Here's the code:

[DllImport("tinyfiledialogs", CharSet = CharSet.Unicode, CallingConvention = CallingConvention.Cdecl)]
private static extern IntPtr tinyfd_selectFolderDialogW([MarshalAs(UnmanagedType.LPTStr)] string aTitle, [MarshalAs(UnmanagedType.LPTStr)] string aDefaultPath = "");

...

outFolderPath = Marshal.PtrToStringUni(tinyfd_selectFolderDialogW("Выберите папку для установки"));

I have tried to use tinyfd_openFileDialogW() with a "Select a folder." (hence the dot) default file name (so it accepts the folder), but this also requires to set ValidateNames to false, which is not possible here.


Solution

  • I just managed to fix it!

    The fix is the [STAThread] attribute for the Main() method:

    [STAThread]
    private static void Main(string[] args)
    {
    

    After I've added it, it worked as expected.

    Updated: the author just added this to the C# example code, and also there is now the selectFolderDialog() method - tinyfiledialogsTest.cs diff