Skip to content

Commit

Permalink
Better fix to foreground window setting issue
Browse files Browse the repository at this point in the history
  • Loading branch information
widavies committed Dec 15, 2022
1 parent 184c9ea commit 43c679f
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions WinJump/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,10 @@ internal static class Program {
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern IntPtr GetTopWindow();
private static extern IntPtr GetForegroundWindow();

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

[STAThread]
public static void Main() {
Expand Down Expand Up @@ -50,6 +53,7 @@ public static void Main() {

// Credit https://stackoverflow.com/a/21684059/4779937
private sealed class STAThread : IDisposable {
private IntPtr[] LastActiveWindow = new IntPtr[10];
private readonly VirtualDesktopWrapper vdw = VirtualDesktopManager.Create();

public STAThread() {
Expand All @@ -73,12 +77,20 @@ public void JumpTo(int index) {
if (ctx == null) throw new ObjectDisposedException("STAThread");

ctx.Send((_) => {
// Before we go to a new Window, save the foreground Window
LastActiveWindow[vdw.GetDesktop()] = GetForegroundWindow();

vdw.JumpTo(index);
// Give it just a little time to let the desktop settle
Thread.Sleep(10);
IntPtr ptr = GetTopWindow();
if (ptr != IntPtr.Zero) {
SetForegroundWindow(ptr);
Thread.Sleep(50);

if(LastActiveWindow[index] != IntPtr.Zero) {
// Check if the window still exists (it might have been closed)
if (IsWindow(LastActiveWindow[index])) {
SetForegroundWindow(LastActiveWindow[index]);
} else {
LastActiveWindow[index] = IntPtr.Zero;
}
}
}, null);
}
Expand Down

0 comments on commit 43c679f

Please sign in to comment.