Moving objects

G

Guest

Can someone tell me how I can move an object, in this case a listbox, over a
form. The code below works, but not when the form is custom sized. It works
perfectly when the form is maximized. And what is the best way to give the
object boundries to move within?

Hope someone can help me.
TIA,
Arjan.

/*Begin Code*/
/*Source: MSDN*/
void ListBox1MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
{
int xOffset;
int yOffset;

if(e.Button == MouseButtons.Left)
{
xOffset = -e.X - SystemInformation.FrameBorderSize.Width;
yOffset = -e.Y - SystemInformation.CaptionHeight -
SystemInformation.FrameBorderSize.Height;
mouseOffset = new Point(xOffset, yOffset);
isMouseDown = true;
}
}

void ListBox1MouseMove(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (isMouseDown)
{
Point mousePos = Control.MousePosition;
mousePos.Offset(mouseOffset.X, mouseOffset.Y);
listBox1.Location = mousePos;
}
}

void ListBox1MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
isMouseDown = false;
}
/*End Code*/
 
S

Stoitcho Goutsev \(100\)

AM,

If I were you I would derive a new class from list box and in this new class
I would override WndProc and process WM_NCHITTEST message to return
HTCAPTION. This way the windows will handle all the moving of the cotnrol.

Here is basically how the WndProc can be written:

private const int WM_NCHITTEST = 0x84;
private const int HTCAPTION = 0x2;
private const int HTCLIENT = 0x1;

protected override void WndProc(ref Message m)
{
base.WndProc (ref m);
if(m.Msg == WM_NCHITTEST && m.Result == new IntPtr(HTCLIENT))
{
m.Result = new IntPtr(HTCAPTION);

}
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

You should check the current position of the mouse and make sure it's inside
the boundary you want.

You should probably need to change from SystemInformation.FrameBorderSize
to another way to get the origin point
 
G

Guest

That's what I tried, but everytime I move the object I get the same result.
The boundries is something I won't have much problems with. But that other
part is causing me a headache.
 

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