Set active window
Asked Answered
C

4

8

I'm trying to make an app that gives a quake style drop-down HUD console. I can get it to show and hide the window, but I can't figure out how to set it as the active window after showing it. Im using Win API calls to show and hide the window. I've tried SetForegroundWindow(IntPtr hWnd) and SetFocus(IntPtr hWnd) to no avail. Anyone have any ideas?

http://pastebin.com/DgtJJGiv

public void ShowApp()
{
    IntPtr h = FindWindow(null, "C:\\Windows\\system32\\cmd.exe");
    ShowWindow(h, SW_SHOW);
    //EnableWindow(h, true);
    isHidden = false;
        // set focus to console window

    SetForegroundWindow(h);
    System.Diagnostics.Debug.WriteLine(h);
}
Citriculture answered 22/6, 2011 at 3:9 Comment(0)
U
4

I found an answer here: How to show form in front in C#

The winAPI approaches were not working correctly for me but this did:

form.TopMost = true;
form.TopMost = false;

I originally was only setting TopMost to true but I ran into problems with dialog boxes displaying behind the form. It appears that setting TopMost to true pulls the form to the front and holds it there. Setting it to false doesn't push it back but does allow other forms to be shown in front. I was still having problems with focus so I ended up going with the following:

form.Activate();
Undersea answered 6/3, 2012 at 15:49 Comment(0)
I
1

Try this (works for me):

public static void ShowApp()
{
    IntPtr h = FindWindow(null, "C:\\Windows\\system32\\cmd.exe");
    ShowWindow(h, ShowWindowCommands.Show);
    SetForegroundWindow(h);
    SetFocus(h);
    System.Diagnostics.Debug.WriteLine(h);
}
Impoverish answered 22/6, 2011 at 3:29 Comment(1)
Setfocus() doesnt grab the focus if you switch to a different application and call the command (I have the showapp() method set to trigger on tilde.) If you dont change the focus between hiding and showing it stays on the console, even while hidden.Citriculture
H
1

You may use SetActiveWindow winAPI method. Hope this helps...

Hurdygurdy answered 22/6, 2011 at 5:3 Comment(0)
A
-1

Is there any reason why you can't implement your own console window? What I mean is a simple Form with a Textbox set to the correct style. You would probably have more control over how it works than trying to use the 'cmd' process.

Just a thought.

Astyanax answered 22/6, 2011 at 4:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.