Help required in understanding an access violation exception

  • Thread starter Thread starter Lee
  • Start date Start date
L

Lee

Hi all, been playing with some code overriding WndProc to get
information about mouse events.
So far I've tried to capture when the left mouse button is pressed
using the code below.

Sometimes the clicks will register fine, and other times it'll cause an
acess violation (Attempted to read or write protected memory. This is
often an indication that other memory is corrupt.)

So I'm wondering why this occurs and how I can prevent it from occuring

[code below]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace Mirach
{
public partial class MirachManager : UserControl
{

private ArrayList objects = new ArrayList();

public MirachManager()
{
InitializeComponent();
}
public void AddControl(object control)
{
objects.Add(control);
this.Invalidate ();
}

public void CheckMousePosition()
{
foreach (_DControl myControl in objects)
{
if ((Cursor.Position.X >= myControl.Top &&
Cursor.Position.X <= myControl.Top + myControl.Height) &&
(Cursor.Position.Y >= myControl.Left && Cursor.Position.Y <=
myControl.Left + myControl.Width))
{
Console.WriteLine("MouseOver");
break;
}
}
}

protected override void OnPaint(PaintEventArgs e)
{
e.Graphics.FillRectangle(new SolidBrush(this.BackColor),
this.Top, this.Left, this.Width, this.Height);
foreach (_DControl myControl in objects)
{
myControl.Draw (e.Graphics);
}
}
private const int WM_LBUTTONDOWN = 0x201;
private const int WM_LBUTTONUP = 0x202;
struct Points
{
public short X;
public short Y;
}
protected override void WndProc(ref
System.Windows.Forms.Message m)
{
System.Windows.Forms.Message myMsg = m;
switch (myMsg.Msg)
{
case WM_LBUTTONDOWN:
Console.WriteLine("Left Mouse Button Down");
Points p = (Points)myMsg.GetLParam(typeof(Points));
Console.WriteLine(p.X);
break;
case WM_LBUTTONUP:
Console.WriteLine("Left Mouse Button Up");
break;
}
//Console.WriteLine(m);
base.WndProc (ref m);
}

private void GameField_Load(object sender, EventArgs e)
{

}
}
}
 
Lee

Im sure someone else will be able to give you a more exact answer but
it will have something to do with the mapping of your struct onto the
L_Param in memory. Something isnt lining up properly which is causing
you access violation

As a fix you can try this code

Int32 result = (Int32)m.LParam;
int xpos = (int)result >> 16;
int ypos = (int)result & 0xFFFF;

(Youll need to check if ive got my x and y the right way round :-)
 
Back
Top