.NET:如何从C#调用CreateProcessAsUser()与STARTUPINFOEXNET、CreateProcessAsUser、STARTUPINFOEX

2023-09-04 06:44:10 作者:煙不離手

大多数样品code调用CreateProcessAsUser()也有类似的PInvoke签名如下:

Most sample code on the web for calling CreateProcessAsUser() has a similar PInvoke signature to the following:

    public static extern bool CreateProcessAsUser(IntPtr hToken,
        string lpApplicationName,
        string lpCommandLine,
        ref SECURITY_ATTRIBUTES lpProcessAttributes,
        ref SECURITY_ATTRIBUTES lpThreadAttributes,
        bool bInheritHandles,
        int creationFlags,
        IntPtr environment,
        string currentDirectory,
        ref STARTUPINFO startupInfo,
        out PROCESS_INFORMATION processInfo);

现在的问题是,我想通过STARTUPINFOEX相反,这是允许在Vista中/ W7。如果我写的C / C ++的话,我可以只投了。

The problem is, I want to pass STARTUPINFOEX instead, which is allowed in Vista/W7. If I was writing C/C++ then I could just cast it.

我应该如何处理这在C#? STARTUPINFOEX看起来是这样的:

How should I deal with this in C#? STARTUPINFOEX looks like this:

    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFOEX
    {
        public STARTUPINFO StartupInfo;
        public IntPtr lpAttributeList;
    };

我应该传递一个IntPtr的结构呢?如果我改变的PInvoke签名,做这样的事情...

Should I be passing an IntPtr to the structure instead? If I change the Pinvoke signature and do something like this...

   IntPtr pStartupInfoEx = Marshal.AllocHGlobal(Marshal.SizeOf(startupInfoEx));
   Marshal.StructureToPtr(startupInfoEx, pStartupInfoEx, true);

。我崩溃我的壳,当我执行CreateProcessAsUser():(

.. I crash my shell when I execute the CreateProcessAsUser() :(

任何想法感激地接受。谢谢你。

Any ideas gratefully received. Thank you.

推荐答案

我觉得你应该把它传递像STARTUPINFO,我的意思是用 REF 关键字。该结构的整编是做了同样的方式,它是针对STARTUPINFO完成。

I think you should just pass it like the STARTUPINFO, I mean with the ref keyword. The marshaling of the structure is done the same way it is done for the STARTUPINFO.