gpt4 book ai didi

c# - PInvoke 创建桌面

转载 作者:太空宇宙 更新时间:2023-11-03 19:36:14 26 4
gpt4 key购买 nike

我正在尝试以传递标志的方式 PInvoke CreateDesktop 以由子进程继承桌面。声明如下:

[DllImport("user32", EntryPoint = "CreateDesktopW", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern IntPtr CreateDesktop(string lpszDesktop, IntPtr lpszDevice, IntPtr pDevmode, int dwFlags,
int dwDesiredAccess, [MarshalAs(UnmanagedType.LPStruct)] SECURITY_ATTRIBUTES lpsa);

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}

我按如下方式使用它:

Win32.SECURITY_ATTRIBUTES sa = new Win32.SECURITY_ATTRIBUTES();
sa.nLength = Marshal.SizeOf(sa);
sa.bInheritHandle = 1;
testDesktopHandle = Win32.CreateDesktop(name, IntPtr.Zero, IntPtr.Zero, 0, Win32.GENERIC_ALL, sa);

不幸的是,它不起作用,我收到以下错误:

System.Runtime.InteropServices.MarshalDirectiveException: Cannot marshal 'parameter #6': Invalid managed/unmanaged type combination (this value type must be paired with Struct).

知道我做错了什么吗?

最佳答案

尝试将参数 #6 更改为

static extern IntPtr CreateDesktop(..., [In] ref SECURITY_ATTRIBUTES lpsa);

(这会编译并且不会在运行时抛出异常,但我仅使用伪造参数对其进行了测试。)

CreateDesktop的C++声明比较:

HDESK WINAPI CreateDesktop(..., __in_opt LPSECURITY_ATTRIBUTES lpsa);
↑ ↑ ↑
[In] ref SECURITY_ATTRIBUTES lpsa

LP 代表“长指针”,即 LPSECURITY_ATTRIBUTES 是指向 SECURITY_ATTRIBUTES 结构的指针。因此,在 C# 中,您需要通过引用传递您的结构实例(值类型)。

关于c# - PInvoke 创建桌面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1434363/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com