jimjim
jimjim

Reputation: 2503

How to set any visible window of other programs to be on top?

What is needed to grab the handle of a visible window and set it to remain on top?

For example being able to set the onTop property of some other application ( let's say notepad) to be on top.

Is there a simple way to do this with Win 7 or 8 ? not really looking for low level trickery with windows API's if possible.

Thank you

Upvotes: 2

Views: 1171

Answers (2)

coding_is_fun
coding_is_fun

Reputation: 1041

HWND_TOPMOST will put the window on to permanently (until some other window is tagged as topmost) but if you want the window to simply pop to the front try:

static readonly IntPtr HWND_TOP = new IntPtr(0);

Upvotes: 0

Reed Copsey
Reed Copsey

Reputation: 564791

You can make a window Topmost given a window handle via:

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

static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
const UInt32 SWP_NOSIZE = 0x0001;
const UInt32 SWP_NOMOVE = 0x0002;
const UInt32 SWP_SHOWWINDOW = 0x0040;

// Call this way:
SetWindowPos(theWindowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);

The method to get the appropriate window handle varies based on the application. You likely can get it via Process.MainWindowHandle, though sometimes it requires using EnumWindows in the Windows API if it's not a "main window".

Using the above, for Notepad, for example, you could do:

var processes = Process.GetProcessesByName("notepad");
SetWindowPos(processes.First().MainWindowHandle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW);

Upvotes: 2

Related Questions