我刚刚开始使用 CsWin32 和我想使用它的 Win32 函数之一 GetWindowText ,它被映射到 我知道如何使用第一个和最后一个参数,但我不知道如何处理中间的
PWSTR lpString
。我如何创建它的实例? PWSTR 的源代码如下所示(摘录):
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*
或等效项?
尝试使用指针。您必须使用
unsafe
和 fixed
。
下面是一个例子。从讨论中复制 (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);
this.logger.WriteLine(windowName);
}
return true;
}
注意:从下面的讨论中复制。