6

One of my coworkers just came to me with an interesting problem.

He's displaying a WinForms form from a PowerShell script, and while the form opens successfully it does not get focus. Instead the PowerShell command window retains focus until the form is explicitly clicked.

The script is being run from the PowerShell command line using .\ScriptName.ps1.

We've tried various combinations of dlg.ShowDialog() (with and without passing $this), dlg.Show(), dlg.Focus(), etc with no luck.

Does anybody know how to give the form focus when it's displayed?

2
  • Is it doing anything else beyond just calling Show()? I imagine the command window just steals the focus back. Try ShowDialog() for example. Commented Oct 14, 2010 at 18:41
  • That's what I expected the problem to be when he explained it to me, too, but he was in fact already using ShowDialog(). The issue turned out to be something deeper, but see my answer below for the solution he found. Commented Oct 14, 2010 at 20:36

2 Answers 2

12

This is how we got it working (the first line is the one we were missing):

$WinForm.Add_Shown({$WinForm.Activate()})
$WinForm.ShowDialog($this) | out-null
Sign up to request clarification or add additional context in comments.

2 Comments

Add_Shown is what I needed, but it doesn't seem to be documented in Powershell
I can't seem to get this to work on Windows 11 in 2025. The dialog is "behind" the console window where the PowerShell script was running. Don't know how to fix it.
0

I was using C# in Powershell. The Add_Shown bit in Redwood's answer translates to adding an event handler for Shown, or simply overriding OnShown:

    protected override void OnShown(EventArgs e)
    {
        base.OnShown(e);
        this.Activate();
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.