Add g_win32_handle_is_console_output()

Private function that checks whether a HANDLE refers to a console
screen buffer.
This commit is contained in:
Luca Bacci
2025-04-16 10:33:02 +02:00
parent e237ec6c81
commit c03f41ca17
2 changed files with 70 additions and 0 deletions

View File

@@ -1453,6 +1453,31 @@ g_win32_find_helper_executable_path (const gchar *executable_name, void *dll_han
return executable_path; 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: * g_win32_handle_is_socket:
* @h: a win32 HANDLE * @h: a win32 HANDLE

45
glib/gwin32private.h Normal file
View File

@@ -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 <http://www.gnu.org/licenses/>.
*
* Author: Luca Bacci <luca.bacci@outlook.com>
*/
#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__ */