Want to show your appreciation? Please to my charity.

Thursday, May 08, 2008

Find the mouse position in WndProc

I had a need to know the mouse position when subclassing the ComboBox (will blog this part later). Googled for it and the best I can get is a post in VB.NET news group. I was hoping a method somewhere in the .Net can easily do this, but I couldn't find it. For now, I have this method below to do the work.
        /// <summary>
        /// Extract the mouse position from mouse related
        /// <see cref="Message">.
        /// </summary>
        /// <param name="mouseMessage"></param>
        /// <returns>Position of the mouse</returns>
        public static Point GetMousePosition(Message mouseMessage)
        {
            int lParam = mouseMessage.LParam.ToInt32();
            int x = (lParam & 0xFFFF);
            int y = (int)(lParam & 0xFFFF0000 >> 16);
            return new Point(x, y);

        }

1 comment:

Richard said...

Rather than the hocus pocus on shifting the the LParm contents and spliting it into integer just to recombine in a point, it can all be done in one step:
[code]
Return new Point(mouseMessage.LParam.ToInt32());
[/code]

An override on WndProc =>
[code]
private int mNCMOUSEMOVE = (int)Enum.Parse(typeof(WM), Enum.GetName(typeof(WM), WM.NCMOUSEMOVE));
private int mNCMOUSELEAVE = (int)Enum.Parse(typeof(WM), Enum.GetName(typeof(WM), WM.NCMOUSELEAVE));
private int mMOUSEMOVE = (int)Enum.Parse(typeof(WM), Enum.GetName(typeof(WM), WM.MOUSEMOVE));
private int mMOUSELEAVE = (int)Enum.Parse(typeof(WM), Enum.GetName(typeof(WM), WM.MOUSELEAVE));
....
protected override void WndProc(ref Message m)
{
if (m.Msg == mMOUSEMOVE || m.Msg == mNCMOUSEMOVE)
{
mMousePosition = new Point(m.LParam.ToInt32());
}
else
{
if (m.Msg == mMOUSELEAVE || m.Msg == mNCMOUSELEAVE)
{
mMousePosition = new Point(-1, -1);
}
base.WndProc(ref m);
}
[/code]

Hope this helps - Wolf5370

Post a Comment