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

时间:2015-06-19 12:02:58

标签: c# windows shell interop

我有以下代码,用于启动任何.exe(在此示例中为notepad.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时它不​​会给我任何语法错误,但它不起作用。

1 个答案:

答案 0 :(得分:1)

您需要深入了解Windows SDK标头,以了解该类型的大小。 例如,对于64位进程,sizeof(HWND)在C ++中为8,而sizeof(int)在C#中为4,因此如果使用int来存储HWND,则会破坏内存。同样适用于HKEY,LPITEMIDLIST,HINSTANCE和HICON。 IntPtr专为此类平台特定的数据类型大小而设计。

编译器不会警告您有关内存损坏等运行时错误的信息。