harriyott.com

Monday, December 11, 2006

FolderBrowseDialog in installer custom actions

Worked round an interesting problem with installer custom actions, where the FolderBrowseDialog displayed the dialog, the buttons and the label, but no directory browse control. The problem turned out to be with threading, as the control is COM, and must run on an STA thread. The installer runs in MTA, so it doesn't work. The way round it is to kick the dialog off in a method running on a new thread, and block until the thread finishes. As well as setting the apartment state explicitly, the STAThread decorator is needed on the method:

private void buttonDir_Click(object sender, EventArgs e)

{

  Thread thread = new Thread(new
    ThreadStart(GetDirectory));

  thread.SetApartmentState(ApartmentState.STA);

  thread.Start();

  thread.Join();

}

[STAThread]
private void GetDirectory()

{

  FolderBrowserDialog folderDlg =
    new
FolderBrowserDialog();

  folderDlg.RootFolder = Environment.SpecialFolder.MyComputer;

  folderDlg.SelectedPath = defaultDirectory;

  folderDlg.ShowNewFolderButton = true;

  if (folderDlg.ShowDialog() == DialogResult.OK)

  {

    selectedPath = folderDlg.SelectedPath;

  }

}

4 Comments:

Anonymous Anonymous said...

good work. looks like a tricky one.

.: secretGeek.net :.

December 22, 2006 4:45 AM  
Anonymous Simon said...

Yeah, it was a little tricky. Pieced it together from two or three forum posts dotted about the place. As ever, I posted it firstly as a reminder to myself, and secondly for people coming across the same problem in the future and googling for it. As a general blog post, it isn't that interesting (I don't think).

December 28, 2006 10:12 AM  
Blogger b said...

Hey,

Thanks, that one saved me some time.

August 01, 2007 6:27 PM  
Anonymous Gerd Blake said...

Hallo,

thanks for your example.
It saved me a lot of time and nerves.
This is an error which you don't expect!

Regards
Gerd Blake

April 24, 2008 2:39 PM  

Post a Comment

Links to this post:

Create a Link

<< Home