Skip to content

GetStdHandle shouldn't return a CloseHandleSafeHandle #91

Closed

Description

@sfiruch

Standard output handles should rarely be closed. Here's Raymond Chen's explanation. Thus, the proper way to use GetStdHandle is by combining it with DangerousAddRef:

var handle = PInvoke.GetStdHandle(STD_HANDLE_TYPE.STD_OUTPUT_HANDLE);
bool ignore=default;
handle.DangerousAddRef(ref ignore);

This could be simplified if GetStdHandle wouldn't return a CloseHandleSafeHandle.

Activity

  1. added
    blocked
    enhancement
    on Feb 16, 2021
  2. AArnott commented on Feb 16, 2021

    @AArnott
    Member

    Great point. I filed microsoft/win32metadata#244 against the metadata so we can do this along with other projections.

  3. AArnott commented on Feb 23, 2021

    @AArnott
    Member

    Now that #143 is done, we actually can create SafeHandle instances with ownsHandle: false set on them.

  4. added a commit that references this issue on May 6, 2022
  5. xPaw commented on Oct 14, 2024

    @xPaw

    I'm curious, how are you expected to pass a handle from GetStdHandle into functions such as GetConsoleMode which expect SafeHandle?

    Use SafeFileHandle or is there a better way of doing it?

    var @out = PInvoke.GetStdHandle(Windows.Win32.System.Console.STD_HANDLE.STD_OUTPUT_HANDLE);
    var safeHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(@out, ownsHandle: false);
    PInvoke.GetConsoleMode(safeHandle, out var mode);
  6. AArnott commented on Oct 15, 2024

    @AArnott
    Member

    Pavel Djundik (@xPaw): it's trivial if you call the GetStdHandle method that returns a SafeHandle:

    SafeHandle safeHandle = PInvoke.GetStdHandle_SafeHandle(default);
    PInvoke.GetConsoleMode(safeHandle, out var mode);
  7. xPaw commented on Oct 15, 2024

    @xPaw

    Ah that's the trick, thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    blockedenhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions