tags:

views:

43

answers:

1

Imagine the code below. Only the first window appears on the top, all of subsequent windows won't nor can they be programatically focused for some reason (they appear in the background). Any idea how to workaround this? BTW, static methods/properties are not allowed nor is any global property.

[STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        Thread t1 = new Thread(CreateForm);
        t1.SetApartmentState(ApartmentState.STA);
        t1.Start();
        t1.Join();

        t1 = new Thread(CreateForm);
        t1.SetApartmentState(ApartmentState.STA);
        t1.Start();
        t1.Join();
    }

    private static void CreateForm()
    {
        using (Form f = new Form())
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer
            {
                Enabled = true,
                Interval = 2000
            };
            t.Tick += (s, e) => { f.Close(); t.Enabled = false; };

            f.TopMost = true;
            Application.Run(f);
        }
    }
A: 

Hans Passant solved the problem: just use SetForegroundWindow() (P/Invoke). Shees, I should have though of that :-)

Miha Markic