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;
    // ...
}

我想我必须这样做

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

但我不知道如何在C#中创建一个char*或等价的代码?

推荐答案

try 使用指针.你必须使用unsafefixed. 下面是一个例子.讨论(https://github.com/microsoft/CsWin32/discussions/181)

没有编译和测试.

   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;
   }

Csharp相关问答推荐

Blazor:类型或命名空间名称Components在命名空间中不存在''

将委托传递到serviceccollection c#web API

如何在C#中删除一个特殊字符,如"使用Regex"

. NET在上一个操作完成之前,在此上下文实例上启动了第二个操作

在C#中,DirectoryEntry返回空AuditRules集合,即使审计规则确实存在

与C#中的Zip列表并行

StackExchange.Redis.RedisServerException:调用ITransaction.ExecuteAsync()时出现错误未知命令取消监视

我如何让我的秒表保持运行场景而不重置

我的MRG32k3a算法实现返回的数字超出了预期的[0,1]范围

如何使用MailKit删除邮箱?

VS 2022 for ASP.NET Core中缺少自定义项模板

在两个已具有一对多关系的表之间添加另一个一对多关系

当try 测试具有协变返回类型的抽象属性时,类似功能引发System.ArgumentException

这是否比决定是否使用ConfigureAWait(False)更好?

是否可以在Entity Framework Core中使用只读 struct 作为拥有实体?

Blazor:搜索框在第一次搜索时不搜索

将J数组转换为列表,只保留一个嵌套的JToken

使用Blazor WebAssembly提高初始页面加载时间的性能

使用SQL Server 2022+时,我是否必须将代码从SqlConnection类对象中迁移出来?

当我在Git中暂存文件更改时,它们会消失