Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending Keyboard inputs to Spotify whilst not in focus

I have an AHK script (below) which sends various commands to the Spotify desktop app globally while in the background to perform various actions, however I play an MMO which has an always running anti-cheat which shuts the game down when it detects AHK because people can use it for macros, etc.

; "CTRL + Alt + UP"  Increase the volume.
^!Up::
DetectHiddenWindows, On
WinGet, winInfo, List, ahk_exe Spotify.exe
Loop, %winInfo%
{
    thisID := winInfo%A_Index%
    ControlFocus , , ahk_id %thisID%
    ControlSend, , ^{up}, ahk_id %thisID%
}
return

The anti-cheat does not detect/care about C# programs/applications so I'm porting over the code to C# and have found a way to send commands to the Spotify application to perform a majority of the stuff I wanted via SendMessage:

private const int WM_KEYDOWN = 0x0100;
private const int WM_KEYUP = 0x0101; //Tried using these to no avail
private const int WM_KEYSYS = 0x0104;
private const int WM_ACTIVATEAPP = 0x001C;

var proc = Process.GetProcessesByName("Spotify").FirstOrDefault(p => !string.IsNullOrWhiteSpace(p.MainWindowTitle));
IntPtr hwnd = proc.MainWindowHandle;
SendMessage(hwnd, 0x0319, (IntPtr)0, (IntPtr)917504);

This command would play/pause the current song as that is what the final number (917504) corresponds to. Spotify also provides command codes for volume up/down, however they affect the entire volume of my PC, not just spotify which is obviously not what I want.

I've tried literally hundreds of combinations of PostMessage and SendMessage and I simply cannot figure out how to send the keys 'Ctrl' + 'Up' to make the volume increase (and vice versa for decrease). while in the background. I don't want the window to be brought to the foreground, etc.

Any help is greatly appreciated.

I also mentioned the AHK script because from my digging I think the ControlSend function is ran from this point in the source code https://github.com/Lexikos/AutoHotkey_L/blob/90b5c2ac3208c38b9488a72fc3e6e4f9cf20b276/source/keyboard_mouse.cpp#L135 , however I don't understand C/C++ enough to be able to figure out how to override the functions that require the window focus, etc.

like image 396
Superduder Avatar asked Jul 14 '20 11:07

Superduder


1 Answers

Maybe think about compiling your AHK script to an exe: It might not be blocked this way. And you would have no effort to transfer your AHK solution.

like image 60
Thierry Dalon Avatar answered Nov 06 '22 07:11

Thierry Dalon