Hi Bob,

The problem is that calling the File dialog use com interop under the hood so the thread you're using needs to be a Single Thread Appartment thread (STA). This is true for a quite a few (but not all) of the winforms controls. The simpliest way round this is to add the STAThread attribute to the entry point of your program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#light
open System
open System.Windows.Forms
open System.IO

let main() =
  let text = "whatever"
  let d = new SaveFileDialog() in 
  d.Filter <- "text files *.txt|*.txt|All files *.*|*.*";
  d.FilterIndex <- 2;
  // d.FileName <- file;
  d.AddExtension <- false; 
  d.OverwritePrompt <- true;
  if d.ShowDialog() = DialogResult.OK then
    let sw = new StreamWriter(d.FileName) in
    sw.Write(text:string); (* type constrain text to resolve sw.Write(_) method overload *)
    sw.Close()
    
[<STAThread>]
do main()

Cheers,
Robert

By on 11/25/2007 1:09 AM ()

Hi, Robert.

Thanks for the reply. My program entry point is in a separate module. After opening the module with the ZTextWindow class, the code is as follows.

[<STAThread()>]
let form = new ZTextWindow()
do Application.Run( form.m_zForm )

The code in my post is a method from the ZTextWindow class.

So I thought I had set up a Single Thread Appartment thread (STA). Am I doing it wrong? Any other ideas?

Thanks for your help. By the way, thanks very much for the book; I'm enjoying it.

Bob

By on 11/25/2007 4:54 PM ()

Attach the attribute to a single do() binding. Unfortunately by specification STAThread can be attached to any function, though really has to go on the "main".

1
2
3
4
5
6
7
 

open System

[<STAThread>]
do()

However I note we could indeed give a warning for your code, where you're not attaching it to a function.

Kind regards

don

By on 11/25/2007 5:09 PM ()

I guess I answered my own question, in a way. I had the code below, which fails.

[<STAThread()>]
let form = new ZTextWindow()
do Application.Run( form.m_zForm )

Switch the top two statements and it works.

let form = new ZTextWindow()
[<STAThread()>]
do Application.Run( form.m_zForm )

I guess I didn't attach it to a function the first time, right?

Thanks to both Robert and Don for your help. I'll keep plugging.

By the way, this little exercise of converting the sample Microsoft editor to a class has taught me a lot.

Bob

By on 11/25/2007 5:21 PM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper