【问题标题】:SetWindowLong/GetWindowLong and 32-bit/64-bit CPUsSetWindowLong/GetWindowLong 和 32 位/64 位 CPU
【发布时间】:2012-03-06 03:20:56
【问题描述】:

我正在使用以下代码:

const int GWL_STYLE = (-16);

const UInt32 WS_POPUP = 0x80000000;
const UInt32 WS_CHILD = 0x40000000;

[DllImport("user32.dll", SetLastError = true)]
static extern UInt32 GetWindowLong(IntPtr hWnd, int nIndex);

[DllImport("user32.dll")]
static extern int SetWindowLong(IntPtr hWnd, int nIndex, UInt32 dwNewLong);

在某个地方……

SetWindowLong(this.Handle, GWL_STYLE,
             ((GetWindowLong(this.Handle, GWL_STYLE) & ~(WS_POPUP)) | WS_CHILD));

这会在 32 位和 64 位机器上正常运行吗?

如果不是,如果我编译我的应用程序以作为 x86 进程运行,它在 64 位机器上仍然可以正常工作吗?

我怎样才能重写以下代码在 32 位和 64 位机器上都可以?

【问题讨论】:

标签: c# winapi 64-bit pinvoke 32-bit


【解决方案1】:

我猜你想知道你是否正确选择了 UInt32 类型。答案是肯定的。文档明确说它始终是 32 位值:http://msdn.microsoft.com/en-us/library/windows/desktop/ms633591(v=vs.85).aspx

你的代码是正确的。

【讨论】:

  • 对,但它也说:"注意这个函数已经被SetWindowLongPtr函数取代了。要编写兼容32位的代码和 64 位版本的 Windows,请使用 SetWindowLongPtr 函数。” 因此,对于 64 位版本的 Windows,仅正确获取 SetWindowLong 的声明是不够的。
  • SetWindowLong 在 64 位平台上仍然可以正常工作,只要您不传递任何正式指针大小的东西(例如,窗口过程)。
  • @Chris: 是的,但是SetWindowLong 函数经常用于传递指针之类的东西......正确编写代码似乎是一个更好的主意第一次这样当你决定重用相同的定义时,你不必记住以后担心它,但这次传递一个指针。
  • @CodyGray:SetWindowLongPtr 是 32 位平台上的宏,因此您不会太远尝试 P/Invoke 它。
  • @CodyGray:您引用了“要编写与 32 位和 64 位版本的 Windows 兼容的代码,请使用 SetWindowLongPtr 函数”。我不认为想象有人在 C#/pinvoke 线程中阅读该引用并认为您打算将其作为 C#/pinvoke 的好建议。尽管您没有这样做,但它很容易被误解(显然是 ChrisV 所为)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-12
  • 2017-06-05
  • 1970-01-01
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多