From 8602bb3b4003dbf5187385f58b29bd87e9468670 Mon Sep 17 00:00:00 2001 From: Adam Sitnik Date: Wed, 17 Jul 2024 15:00:56 +0200 Subject: [PATCH] Console beep: perform the sys-call directly (#104966) --- .../src/System/ConsolePal.Windows.cs | 27 ++++++------------- 1 file changed, 8 insertions(+), 19 deletions(-) diff --git a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs index 2edf2da4cebb6..49f2d42b97fe8 100644 --- a/src/libraries/System.Console/src/System/ConsolePal.Windows.cs +++ b/src/libraries/System.Console/src/System/ConsolePal.Windows.cs @@ -677,28 +677,17 @@ public static unsafe string Title public static void Beep() { - const char BellCharacter = '\u0007'; // Windows doesn't use terminfo, so the codepoint is hardcoded. - if (!Console.IsOutputRedirected) { - Console.Out.Write(BellCharacter); - return; - } - - if (!Console.IsErrorRedirected) - { - Console.Error.Write(BellCharacter); - return; + ReadOnlySpan bell = "\u0007"u8; // Windows doesn't use terminfo, so the codepoint is hardcoded. + int errorCode = WindowsConsoleStream.WriteFileNative(OutputHandle, bell, useFileAPIs: Console.OutputEncoding.CodePage != UnicodeCodePage); + if (errorCode == Interop.Errors.ERROR_SUCCESS) + { + return; + } } - BeepFallback(); - } - - private static void BeepFallback() - { - const int BeepFrequencyInHz = 800; - const int BeepDurationInMs = 200; - Interop.Kernel32.Beep(BeepFrequencyInHz, BeepDurationInMs); + Interop.Kernel32.Beep(frequency: 800, duration: 200); } public static void Beep(int frequency, int duration) @@ -1226,7 +1215,7 @@ private static unsafe int ReadFileNative(IntPtr hFile, Span buffer, bool i return errorCode; } - private static unsafe int WriteFileNative(IntPtr hFile, ReadOnlySpan bytes, bool useFileAPIs) + internal static unsafe int WriteFileNative(IntPtr hFile, ReadOnlySpan bytes, bool useFileAPIs) { if (bytes.IsEmpty) return Interop.Errors.ERROR_SUCCESS;