GetWindowLong vs GetWindowLongPtr in C#
Asked Answered
N

3

4

I was using GetWindowLong like this:

[DllImport("user32.dll")]
private static extern IntPtr GetWindowLong(IntPtr hWnd, int nIndex);

But according to the MSDN docs I am supposed to be using GetWindowLongPtr to be 64bit compatible. http://msdn.microsoft.com/en-us/library/ms633584(VS.85).aspx

The MSDN docs for GetWindowLongPtr say that I should define it like this (in C++):

LONG_PTR GetWindowLongPtr(HWND hWnd, int nIndex);

I used to be using IntPtr as the return type, but what the heck would I use for an equivalent for LONG_PTR? I have also seen GetWindowLong defined as this in C#:

[DllImport("user32.dll")]
private static extern long GetWindowLong(IntPtr hWnd, int nIndex);

What is right, and how can I ensure proper 64bit compatibility?

Nor answered 26/11, 2008 at 3:30 Comment(1)
Both these DllImport statements are incorrect: on 64-bit Windows, GetWindowLong doesn't return an IntPtr, and on 32-bit Windows, GetWindowLong doesn't return a long.Reorder
D
7

Unfortunately it's not that easy, because GetWindowLongPtr doesn't exist in 32bit Windows. On 32bit systems GetWindowLongPtr is just a C macro that points to GetWindowLong. If you really need to use GetWindowLongPtr on both 32 and 64 bit systems you'll have to determine the correct one to call at run time. See the description at pinvoke.net

Dahliadahlstrom answered 26/11, 2008 at 8:22 Comment(0)
U
8

You should define GetWindowLongPtr using an IntPtr. In C/C++ a LONG_PTR is 32-bits on a 32-bit system and 64-bits on a 64-bit system (see here). IntPtr in C# is designed to work the same way (see here).

So what you want is:

[DllImport("user32.dll")]
private static extern IntPtr GetWindowLongPtr(IntPtr hWnd, int nIndex);
Unrounded answered 26/11, 2008 at 3:43 Comment(0)
D
7

Unfortunately it's not that easy, because GetWindowLongPtr doesn't exist in 32bit Windows. On 32bit systems GetWindowLongPtr is just a C macro that points to GetWindowLong. If you really need to use GetWindowLongPtr on both 32 and 64 bit systems you'll have to determine the correct one to call at run time. See the description at pinvoke.net

Dahliadahlstrom answered 26/11, 2008 at 8:22 Comment(0)
N
3

SoapBox is correct.

Additionally, if you ever need to see how a type or function should Marshal in Win32, try using the PInvoke Interop Assistant. It will has built-in generations for most Win32 API's and can do custom generation based off of code snippets.

Neoimpressionism answered 26/11, 2008 at 4:19 Comment(2)
Thanks for the excellent link - I think I just found a new favourite utility.Nor
The CodePlex link is broken. You may want to link your Github repo now? github.com/jaredpar/pinvoke-interop-assistantAlamo

© 2022 - 2024 — McMap. All rights reserved.