Search code examples
c#winapipinvoke

CsWin32 how to create an instance of PWSTR for e.g. GetWindowText


I just started using CsWin32 and one of the Win32 functions I want to use it GetWindowText which gets mapped to enter image description here I know how to work with the first and last parameter, but I don't know what to do with the one in the middle, the PWSTR lpString. How do I create an instance of that? The source code for PWSTR looks like this (excerpt):

internal unsafe readonly partial struct PWSTR
    : IEquatable<PWSTR>
{
    // ...
    internal PWSTR(char* value) => this.Value = value;
    // ...
}

Guess I have to so something like

PWSTR lpString = new PWSTR(<what to do here>);

but I don't know how to create a char* or equivalent in C# ?


Solution

  • Try using pointers. You have to use unsafe and fixed. Below is an example. Copied from a discussion (https://github.com/microsoft/CsWin32/discussions/181)

    Not compiled and tested.

       int bufferSize = PInvoke.GetWindowTextLength(handle) + 1;
       unsafe // BELOW CODE INVOLVES POINTERS.
       {
           //ADDRESS WONT CHANGE, THIS VARIABLE SHOULD BE USED WITH IN THIS SCOPE.
           fixed (char* windowNameChars = new char[bufferSize]) 
           {
               if (PInvoke.GetWindowText(handle, windowNameChars, bufferSize) == 0)
               {
                   int errorCode = Marshal.GetLastWin32Error();
                   if (errorCode != 0)
                   {
                       throw new Win32Exception(errorCode);
                   }
    
                   return true;
               }
    
               string windowName = new string(windowNameChars);
           }
    
           return true;
       }