Marshal.PtrToStructure crashes

  • Thread starter Thread starter Tyron
  • Start date Start date
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);
}
 
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.
 
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
 
Back
Top