Marshal.PtrToStructure crashes

T

Tyron

I want to get the Position of the Mouse when the User click in the
non-client area of a Window.
WM_NCLBUTTONDOWN seems to be the right Message for this - and the LParam
contains a POINTS struct of the Mouse Position (so the speak on MSDN.
[http://msdn.microsoft.com/library/d...rence/mouseinputmessages/wm_nclbuttondown.asp])
But when I try to convert the IntPtr to a Struct, it throws a
Argument.NullReferenceException
Code:


[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct POINT {
public Int16 x;
public Int16 y;
}

protected override void WndProc(ref Message m)
{
if(m.Msg==WM_NCLBUTTONDOWN) {
POINT pnt = new POINT();
// crashes
pnt = (POINT)Marshal.PtrToStructure(m.LParam,typeof(POINT));
// label2.Text = pnt.x + "/" + pnt.y;
}
base.WndProc(ref m);
}
 
D

Dave

I belive the X and Y coords of the unmanged Point structure are 32 bit integers.

You can use System.Windows.Forms.Control.MousePosition as an easier solution.
 
J

John Sun

Tyron said:
I want to get the Position of the Mouse when the User click in the
non-client area of a Window.
WM_NCLBUTTONDOWN seems to be the right Message for this - and the LParam
contains a POINTS struct of the Mouse Position (so the speak on MSDN.
[http://msdn.microsoft.com/library/d...rence/mouseinputmessages/wm_nclbuttondown.asp])
But when I try to convert the IntPtr to a Struct, it throws a
Argument.NullReferenceException
Code:


[StructLayout(LayoutKind.Sequential, CharSet=CharSet.Ansi)]
public struct POINT {
public Int16 x;
public Int16 y;
}

protected override void WndProc(ref Message m)
{
if(m.Msg==WM_NCLBUTTONDOWN) {
POINT pnt = new POINT();
// crashes
pnt = (POINT)Marshal.PtrToStructure(m.LParam,typeof(POINT));
// label2.Text = pnt.x + "/" + pnt.y;
}
base.WndProc(ref m);
}
System.Drawing.Point actually takes m.LParam in one of its
constructor, I think this may be a easier way for you to get the positon.

HTH.

Jianwei
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top