Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JokerMartini/2415387ecd957e7f038b to your computer and use it in GitHub Desktop.
Save JokerMartini/2415387ecd957e7f038b to your computer and use it in GitHub Desktop.
C#: Get last in focus windows application by name and bring to the foreground
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace focusOrder
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GetZOrder();
}
enum GetWindow_Cmd : uint
{
GW_HWNDFIRST = 0,
GW_HWNDLAST = 1,
GW_HWNDNEXT = 2,
GW_HWNDPREV = 3,
GW_OWNER = 4,
GW_CHILD = 5,
GW_ENABLEDPOPUP = 6
}
[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr GetWindow(IntPtr hWnd, GetWindow_Cmd uCmd);
private IntPtr GetTopmostHwnd(List<IntPtr> hwnds)
{
var topmostHwnd = IntPtr.Zero;
if (hwnds != null && hwnds.Count > 0)
{
var hwnd = hwnds[0];
while (hwnd != IntPtr.Zero)
{
if (hwnds.Contains(hwnd))
{
topmostHwnd = hwnd;
}
hwnd = GetWindow(hwnd, GetWindow_Cmd.GW_HWNDPREV);
}
}
return topmostHwnd;
}
private List<IntPtr> GetProcsHandlesByName(string name = "")
{
List<IntPtr> hwdList = new List<IntPtr>();
Process[] procs = Process.GetProcessesByName(name);
foreach (Process p in procs)
{
IntPtr handle = p.MainWindowHandle;
if (handle != IntPtr.Zero)
{
hwdList.Add(handle);
}
}
return hwdList;
}
[DllImport("user32.dll")]
static extern bool SetForegroundWindow(IntPtr hWnd);
private void GetZOrder()
{
IntPtr TopHandle = GetTopmostHwnd(GetProcsHandlesByName("notepad"));
Console.WriteLine(TopHandle);
// test
SetForegroundWindow(TopHandle);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment