Skip to content

Commit ef5df7f

Browse files
committed
Adding webui_win32_get_hwnd
1 parent 5d497e3 commit ef5df7f

File tree

2 files changed

+60
-1
lines changed

2 files changed

+60
-1
lines changed

include/webui.h

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -795,6 +795,18 @@ WEBUI_EXPORT size_t webui_get_parent_process_id(size_t window);
795795
*/
796796
WEBUI_EXPORT size_t webui_get_child_process_id(size_t window);
797797

798+
/**
799+
* @brief Gets Win32 window `HWND`. More reliable with WebView
800+
* than web browser window, as browser PIDs may change on launch.
801+
*
802+
* @param window The window number
803+
*
804+
* @return Returns the window `hwnd` as `void*`
805+
*
806+
* @example HWND hwnd = webui_win32_get_hwnd(myWindow);
807+
*/
808+
WEBUI_EXPORT void* webui_win32_get_hwnd(size_t window);
809+
798810
/**
799811
* @brief Get the network port of a running window.
800812
* This can be useful to determine the HTTP link of `webui.js`

src/webui.c

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2633,6 +2633,54 @@ size_t webui_get_child_process_id(size_t window) {
26332633
#endif
26342634
}
26352635

2636+
void* webui_win32_get_hwnd(size_t window) {
2637+
2638+
#ifdef WEBUI_LOG
2639+
printf("[User] webui_win32_get_hwnd([%zu])\n", window);
2640+
#endif
2641+
2642+
// Initialization
2643+
_webui_init();
2644+
2645+
// Dereference
2646+
if (_webui_mutex_app_is_exit_now(WEBUI_MUTEX_GET_STATUS) || _webui.wins[window] == NULL)
2647+
return NULL;
2648+
_webui_window_t* win = _webui.wins[window];
2649+
2650+
#ifdef _WIN32
2651+
if (_webui.is_webview) {
2652+
// WebView Window
2653+
if (win->webView) {
2654+
return win->webView->hwnd;
2655+
}
2656+
return NULL;
2657+
} else {
2658+
// Web Browser Window
2659+
size_t child_pid = webui_get_child_process_id(window);
2660+
if (child_pid == 0) {
2661+
return NULL;
2662+
}
2663+
HWND hwnd = NULL;
2664+
int max_iterations = 10000;
2665+
do {
2666+
hwnd = FindWindowEx(NULL, hwnd, NULL, NULL);
2667+
if (hwnd == NULL) {
2668+
break;
2669+
}
2670+
DWORD pid;
2671+
GetWindowThreadProcessId(hwnd, &pid);
2672+
if (pid == child_pid) {
2673+
return hwnd;
2674+
}
2675+
} while (--max_iterations > 0);
2676+
return NULL;
2677+
}
2678+
#endif
2679+
2680+
// This API is only available on Windows
2681+
return NULL;
2682+
}
2683+
26362684
void webui_set_hide(size_t window, bool status) {
26372685

26382686
#ifdef WEBUI_LOG
@@ -2821,7 +2869,6 @@ void webui_set_profile(size_t window, const char* name, const char* path) {
28212869
win->default_profile = false;
28222870
}
28232871

2824-
28252872
void webui_set_proxy(size_t window, const char* proxy_server) {
28262873

28272874
#ifdef WEBUI_LOG

0 commit comments

Comments
 (0)