segatools/common/util/fg-detect.c
kyoubate-haruka b86049034f Add setting to only allow game input in foreground (#83)
This adds a setting to the global configuration to allow only input when the game is focused. This prevents issues, such as triggering game buttons or service buttons while being tabbed out. Turned off by default.

The implementation is not the best, but in the context how these games are structured, the most acceptable.
It will keep scanning if the foreground window title fully matches (some games partially match, like FGO because due to the revision number in the title), and if found, will grab the HWND of that window and compare that from then on, to not tank performance due to constant string operations.

Tested with FGO, chusan and ongeki.

Reviewed-on: https://gitea.tendokyu.moe/TeamTofuShop/segatools/pulls/83
Reviewed-by: Dniel97 <dniel97@noreply.gitea.tendokyu.moe>
Co-authored-by: kyoubate-haruka <46010460+kyoubate-haruka@users.noreply.github.com>
Co-committed-by: kyoubate-haruka <46010460+kyoubate-haruka@users.noreply.github.com>
2025-11-12 22:33:32 +00:00

67 lines
1.6 KiB
C

#include <stdbool.h>
#include <windows.h>
#include "util/dprintf.h"
#include "util/fg-detect.h"
#include <assert.h>
static HWND window_handle;
static const wchar_t* window_title = NULL;
static bool foreground_state = true;
static bool partial_match;
static wchar_t scanned_title[256];
static HWND get_window(){
if (window_handle != NULL){
return window_handle;
}
// try detecting the window
HWND hwnd = GetForegroundWindow();
if (GetWindowTextW(hwnd, scanned_title, sizeof(scanned_title)) == 0) {
return NULL;
}
if (partial_match) {
if (wcsstr(scanned_title, window_title) == NULL) {
return NULL;
}
} else {
if (wcscmp(scanned_title, window_title) != 0) {
return NULL;
}
}
dprintf("FG-Detect: Program window detected\n");
window_handle = hwnd;
return window_handle;
}
void fgdet_init(const wchar_t* wnd_title, const bool wnd_partial_match) {
assert(wnd_title != NULL);
window_handle = NULL;
window_title = wnd_title;
partial_match = wnd_partial_match;
dprintf("FG-Detect: Searching for \"%ls\"\n", window_title);
}
bool fgdet_in_foreground(){
return foreground_state;
}
void fgdet_poll(){
if (window_title == NULL){
return;
} else if (GetForegroundWindow() == get_window()){
if (!foreground_state){
dprintf("FG-Detect: Got focus\n");
foreground_state = true;
}
} else {
if (foreground_state){
dprintf("FG-Detect: Lost focus\n");
foreground_state = false;
}
}
}