ganders
ganders

Reputation: 7442

Move external application to the front of the screen

The application that I'm running needs to call a separate app to do some scanning. I'm calling the other application by starting a new System.Diagnostics.Process. Once I get that process, I call a method to give that application the focus. I've tried two different ways to give that external app the focus, but neither are working. Could someone help?

Here's the code:

using System.Runtime.InteropServices;

    [DllImport("user32.dll")]
    private static extern bool ShowWindow(IntPtr hWnd, uint windowStyle);

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(IntPtr hWnd, 
      IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);

    [DllImport("user32.dll")]
    private static extern bool SetForegroundWindow(IntPtr hWnd);

    private static void GiveSpecifiedAppTheFocus(int processID)
    {
        try
        {
            Process p = Process.GetProcessById(processID);

            ShowWindow(p.MainWindowHandle, 1);
            SetWindowPos(p.MainWindowHandle, new IntPtr(-1), 0, 0, 0, 0, 3);

            //SetForegroundWindow(p.MainWindowHandle);
        }
        catch
        {
            throw;
        }
    }

First scenario uses the ShowWindow and SetWindowPos methods, the other method uses the SetForegroundWindow method. Neither will work...

Am I using the wrong methods, or do I have an error in the code that I'm using? Thanks all!

Upvotes: 4

Views: 5481

Answers (2)

Dan Gifford
Dan Gifford

Reputation: 896

Try setting your process to the background ie: this.SendToBack(); This is just another solution, partial fix.

Upvotes: 0

Flot2011
Flot2011

Reputation: 4671

Use SetWindowPos, but whenever you don't want the window to be the topmost anymore call it again with the second parameter set to -2 (HWND_NOTOPMOST) instead of -1(HWND_TOPMOST)

Upvotes: 4

Related Questions