manuelmayer-dev / Macro-Deck-Windows-Utils-Plugin

A collection of some useful functions for controlling Windows
MIT License
9 stars 15 forks source link

`Start/Focus` method not focusing application #31

Open VLTNOgithub opened 8 months ago

VLTNOgithub commented 8 months ago

Info

OS: Windows 10 22H2 Macro Deck Version: 2.14.1 Client: Android (13)

Steps to Reproduce

  1. Select the Start/Focus method in Start Application
  2. Open the application (either outside of Macro Deck or using the button, it doesn't matter)
  3. The already opened application does not focus when clicking the button

The Issue

The SetForegroundWindow function only works in certain cases. Provided is an image of the requirements that are the main reason as to why the function doesn't work in most cases: conditions SetForegroundWindow documentation here.

The Fix

I used the ShowWindow function, which is already used in the code, to activate the window (SW_SHOW) and then show its default state (SW_SHOWDEFAULT). ShowWindow documentation here.

Using this information, I have (somewhat) fixed the implementation of the BringToForeground function in the ApplicationLauncher.cs file. This does not restore it in the most recent position or state. It only restores it to the state it was in when first opened.

Updated function:

public static void BringToForeground(string path)
{
    path = WindowsShortcut.GetShortcutTarget(path);
    if (!IsRunning(path)) return;
    var p = GetProcessByPath(path);
    if (p == null) return;

    IntPtr handle = p.MainWindowHandle;
    ShowWindow(handle, 5);    // Changes here
    ShowWindow(handle, 10);  // Changes here
    if (!IsIconic(handle))
    {
            return;
    }
    MinimizeAndRestoreWindow(handle); // Fallback function
}

The changes are in pull request #33.

kapitanluffy commented 5 months ago

What do you think is the problem with the previous code?

Also, I am curious if this is related https://github.com/Macro-Deck-App/Macro-Deck/issues/232

VLTNOgithub commented 4 months ago

What do you think is the problem with the previous code?

The previous code uses the function SetForegroundWindow from the Windows API. Referring to the documentation, it only works if Macro Deck is the foreground (focused) application or there is no foreground application (there's more but these are the main two).

SetForegroundWindow Documentation conditions

TLDR; SetForegroundWindow needs Macro Deck to be focused but 9.9999 times out of 10, its not.