如果某些参数只是 int 类型,则 ShellExecute 不起作用



我有以下代码,用于启动任何.exe(在本例中为记事本.exe)。但是此代码不起作用。虽然没有编译问题。

    [DllImport("shell32.dll", CharSet = CharSet.Auto)]
    static extern bool ShellExecuteEx(ref SHELLEXECUTEINFO lpExecInfo);
    public static void exev()
    {
        SHELLEXECUTEINFO info = new SHELLEXECUTEINFO();
        info.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(info);
        info.lpVerb = "open";
        info.lpFile = "c:\windows\notepad.exe";
        info.nShow = 5;
        info.fMask = 0x440;
        info.hwnd = IntPtr.Zero;
        ShellExecuteEx(ref info);
    }
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
    public int cbSize;
    public uint fMask;
    public IntPtr hwnd;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpVerb;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpFile;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpParameters;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpDirectory;
    public int nShow;
    public int hInstApp;
    public int lpIDList;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpClass;
    public int hkeyClass;
    public uint dwHotKey;
    public int hIcon;
    public int hProcess;
}

我尝试了下面的代码,其中我更改了 SHELLEXECUTEINFO 结构,然后它开始工作。我所做的更改将变量hInstApp,lpIDList,hkeyClass,hIcon和hProcess从int重命名为inptr。

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct SHELLEXECUTEINFO
{
    public int cbSize;
    public uint fMask;
    public IntPtr hwnd;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpVerb;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpFile;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpParameters;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpDirectory;
    public int nShow;
    public IntPtr hInstApp;
    public IntPtr lpIDList;
    [MarshalAs(UnmanagedType.LPTStr)]
    public string lpClass;
    public IntPtr hkeyClass;
    public uint dwHotKey;
    public IntPtr hIcon;
    public IntPtr hProcess;
}

我想知道我们是否可以让它仅适用于这些变量的 int 数据类型。还是它仅适用于 IntPtr?除了数据类型大小之外,它们在此方案中有何不同?因为当我只对hInstApp,lpIDList,hkeyClass,hIcon和hProcess变量使用int时,它不会给我任何语法错误,但它不起作用。

您需要深入研究 Windows SDK 标头以查看类型有多大。例如,对于 64 位进程,sizeof(HWND) 在 C++ 中为 8,在 C# 中为 4,因此如果使用 int 存储 HWND,则会损坏内存。HKEY、LPITEMIDLIST、HINSTANCE 和 HICON 也是如此。IntPtr 专为这种特定于平台的数据类型大小而设计。

编译器不会警告运行时错误,如内存损坏。

最新更新