【问题标题】:How to convert IntPtr to int如何将 IntPtr 转换为 int
【发布时间】:2013-08-12 22:49:44
【问题描述】:

窗口句柄有时为int 类型,有时为IntPtr 类型

int 示例:

 [DllImport("user32.dll")]
    static extern uint GetWindowThreadProcessId(int hWnd, int ProcessId);    

IntPtr 示例:

  [DllImport("user32.dll", CharSet = CharSet.Auto)]
    static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam);

我似乎无法从一个转换/转换到另一个。

当我尝试this.ProcessID = GetWindowThreadProcessId(windowHandle.ToInt32(),0) 时,我收到错误cannot implicitly convert from uint to int

【问题讨论】:

  • windowHandle.ToInt32() 会起作用。
  • @Henk holterman 我编辑了问题,但仍然没有编译
  • 你不应该编辑掉问题的关键部分,添加下一部分。
  • 检查你的this.ProcessID声明

标签: c# window-handles


【解决方案1】:

无论何时,我都会收到“算术运算导致溢出”:

IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler.ToInt32() == 0) //throws Exception

而不是那个:

IntPtr handler = OpenSCManager(null, null, SC_MANAGER_CREATE_SERVICE);
if (handler == IntPtr.Zero) //OK

【讨论】:

    【解决方案2】:

    SendMessage 签名是

    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    

    或者这个

    static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, StringBuilder lParam);
    

    不要交换intIntPtr。它们仅在 32 位(大小相等)上几乎相等。在 64 位时,IntPtr 几乎等同于 long(大小相等)

    GetWindowThreadProcessId 签名是

    static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
    

    static extern uint GetWindowThreadProcessId(IntPtr hWnd, IntPtr ProcessId);
    

    在这种情况下,“某物”的refout 是对某物的托管引用,因此当传递给本机API 时,它们会在内部转换为IntPtr。所以out uint从Native API的角度来看,相当于IntPtr

    解释:重要的是参数的“长度”是正确的。 intuint 对于被调用的 API 是相等的。 32 位的IntPtr 也是一样的。

    请注意,某些类型(如 boolchar)由编组器进行特殊处理。

    您不应该将int 转换为IntPtr。将其保留为IntPtr 并快乐地生活。如果您必须进行一些 IntPtr 不支持的数学运算,请使用 long(它是 64 位,所以在我们拥有 Windows 128 之前,不会有任何问题 :-)) .

    IntPtr p = ...
    long l = (long)p;
    p = (IntPtr)l;
    

    【讨论】:

      【解决方案3】:

      我认为错误cannot implicitly convert from uint to int 指的是= 语句。字段this.ProcessIDint,但GetWindowThreadProcessId 返回uint

      试试这个

      this.ProcessID = unchecked((int)GetWindowThreadProcessId(windowHandle.ToInt32(),0))
      

      【讨论】:

        猜你喜欢
        • 2010-10-20
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        • 2010-09-07
        • 2016-12-07
        • 1970-01-01
        • 2010-10-23
        • 1970-01-01
        相关资源
        最近更新 更多