赢API在C#。得到的IntPtr Hi和低字 [英] Win api in C#. Get Hi and low word from IntPtr

查看:181
本文介绍了赢API在C#。得到的IntPtr Hi和低字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想处理在C#中WM_MOUSEMOVE消息。

I am trying to process a WM_MOUSEMOVE message in C#.

什么是正确的方式来获得一个X和lParam的Y坐标这是一种IntPtr的吗?

What is the proper way to get an X and Y coordinate from lParam which is a type of IntPtr?

推荐答案

尝试:
结果的(注意,这是最初的版本,下面阅读的最终版本)

IntPtr xy = value;
int x = unchecked((short)xy);
int y = unchecked((short)((uint)xy >> 16));



选中通常是没有必要的(因为默认C#项目未选中)

The unchecked normally isn't necessary (because the "default" c# projects are unchecked)

考虑到这些都是用宏的定义:

Consider that these are the definitions of the used macros:

#define LOWORD(l) ((WORD)(((DWORD_PTR)(l)) & 0xffff))
#define HIWORD(l) ((WORD)((((DWORD_PTR)(l)) >> 16) & 0xffff))

#define GET_X_LPARAM(lp) ((int)(short)LOWORD(lp))
#define GET_Y_LPARAM(lp) ((int)(short)HIWORD(lp))

其中, WORD == USHORT DWORD == UINT 。我切割一些ushort->短的转换

Where WORD == ushort, DWORD == uint. I'm cutting some ushort->short conversions.

附录:

一年半后,并在经历了64位.NET变幻莫测,我同意Celess(但要注意,Windows消息的99%,仍然是兼容的原因32位,所以我不认为这个问题是不是现在真的很大,它是更多的未来,因为如果你想要做的事,你应该做是正确的。)

one and half year later, and having experienced the "vagaries" of 64 bits .NET, I concur with Celess (but note that 99% of the Windows messages are still 32 bits for reasons of compatibility, so I don't think the problem isn't really big now. It's more for the future and because if you want to do something, you should do it correctly.)

我唯一会做出不同的是这样的:

The only thing I would make different is this:

IntPtr xy = value;
int x = unchecked((short)(long)xy);
int y = unchecked((short)((long)xy >> 16));



而不是做检查是的IntPtr 4个或8个字节长,我把最坏的情况(8字节长)和铸造 XY 。随着一点点运气双投(以再到 /到 UINT )将被编译器优化(在结束时,显式转换为 INT 的IntPtr 是一个红鲱鱼......如果你使用它,你是把自己处于危险的未来。你应该始终使用转换,然后直接使用它/重它转换为你需要什么,展示给你未来的程序员的知道的你在做什么

instead of doing the check "is the IntPtr 4 or 8 bytes long", I take the worst case (8 bytes long) and cast xy to a long. With a little luck the double cast (to long and then to short/to uint) will be optimized by the compiler (in the end, the explicit conversion to int of IntPtr is a red herring... If you use it you are putting yourself at risk in the future. You should always use the long conversion and then use it directly/re-cast it to what you need, showing to the future programmers that you knew what you were doing.

一个测试,例如:的 http://ideone.com/a4oGW2 (可惜只有32位,但如果你有一个64位的机器可以测试相同的代码)

A test example: http://ideone.com/a4oGW2 (sadly only 32 bits, but if you have a 64 bits machine you can test the same code)

这篇关于赢API在C#。得到的IntPtr Hi和低字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆