diff --git a/glib/gwin32.c b/glib/gwin32.c index bbee611d3..7e6c70c93 100644 --- a/glib/gwin32.c +++ b/glib/gwin32.c @@ -1453,6 +1453,31 @@ g_win32_find_helper_executable_path (const gchar *executable_name, void *dll_han return executable_path; } +bool +g_win32_handle_is_console_output (HANDLE handle, + bool log_errors) +{ + /* MSDN suggests using GetConsoleMode() to check if a HANDLE refers to + * the console. However, GetConsoleMode() requires read access rights + * (FILE_READ_DATA | FILE_READ_ATTRIBUTES | FILE_READ_EA on Windows 10) + * and output HANDLEs may be opened with write rights only. To overcome + * that we use WriteConsole() with a zero characters count. + */ + const wchar_t *dummy = L""; + if (!WriteConsole (handle, dummy, 0, NULL, NULL)) + { + if (log_errors && + GetLastError () != ERROR_INVALID_HANDLE) + { + WIN32_API_FAILED ("WriteConsole"); + } + + return false; + } + + return true; +} + /* * g_win32_handle_is_socket: * @h: a win32 HANDLE diff --git a/glib/gwin32private.h b/glib/gwin32private.h new file mode 100644 index 000000000..81220b77b --- /dev/null +++ b/glib/gwin32private.h @@ -0,0 +1,45 @@ +/* + * Copyright © 2025 Luca Bacci + * + * SPDX-License-Identifier: LGPL-2.1-or-later + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, see . + * + * Author: Luca Bacci + */ + +#ifndef __G_WIN32PRIVATE_H__ +#define __G_WIN32PRIVATE_H__ + +#ifdef G_PLATFORM_WIN32 + +#include "config.h" + +/** < private > + * + * g_win32_handle_is_console_output: + * + * @handle: the given HANDLE + * @log_errors: whether to log unexpected errors + * + * Checks if the given HANDLE refers to a Win32 console screen + * buffer (output HANDLE). + */ +bool +g_win32_handle_is_console_output (HANDLE handle, + bool log_errors); + +#endif /* G_PLATFORM_WIN32 */ + +#endif /* __G_WIN32PRIVATE_H__ */