OnMove for a UserControl

  • Thread starter Thread starter Guest
  • Start date Start date
Seems like it inherits from Control which has a OnMove handler, but I never
get it.
 
Works fine for me...

Note that this is relative to the container, so if the container is
moved you won't get it... you'd need to attach events all the way up
to the form to catch this.


using System;
using System.Windows.Forms;
using System.Drawing;

class Test : UserControl {
static void Main() {
Random rand = new Random();
using(Form f = new Form())
using(Button b = new Button())
using (Test t = new Test()) {
b.Dock = DockStyle.Top;
f.Controls.Add(b);
f.Controls.Add(t);
b.Text = "Move";
b.Click += delegate {
t.Location = new Point(rand.Next(f.Width),
rand.Next(f.Height));
};
Application.Run(f);
}
}

protected override void OnMove(EventArgs e) {
ParentForm.Text = "OnMove:" + Location;
}
}
 
To complete this to detect a change at any level:

using System;
using System.Windows.Forms;
using System.Drawing;
using System.Collections.Generic;

class Test : UserControl {
static void Main() {
Random rand = new Random();
using(Form f = new Form())
using(Button b = new Button())
using (Test t = new Test()) {
b.Dock = DockStyle.Top;
f.Controls.Add(b);
f.Controls.Add(t);
b.Text = "Move";
b.Click += delegate {
t.Location = new Point(rand.Next(f.Width),
rand.Next(f.Height));
};
Application.Run(f);
}
}
private readonly List<Control> hierarchy = new List<Control>();
private void Bind(bool hook) {
foreach(Control c in hierarchy) { // detach first
c.Move -= c_Move;
c.ParentChanged -= c_ParentChanged;
}
hierarchy.Clear();
if (hook) { // re-attach if desired
Control c = Parent; // could equally start with self and
drop 2xOn[blah]
while (c != null) {
c.Move += c_Move;
c.ParentChanged += c_ParentChanged;
hierarchy.Add(c);
c = c.Parent;
}
YeehahMoved();
}

}
protected override void Dispose(bool disposing) {
if (disposing) {
Bind(false);
}
base.Dispose(disposing);
}
void c_ParentChanged(object sender, EventArgs e) {
Bind(true); // hierarchy has changed...
}

void c_Move(object sender, EventArgs e) {
YeehahMoved(); // somebody moved and it wasn't us!
}

private void YeehahMoved() {
if(ParentForm!=null) ParentForm.Text =
PointToScreen(Location).ToString();
}

public Test() { // make it visible
BorderStyle = BorderStyle.FixedSingle;
}

protected override void OnParentChanged(EventArgs e) {
base.OnParentChanged(e);
Bind(true);
}

protected override void OnMove(EventArgs e) {
base.OnMove(e);
YeehahMoved();
}
}
 
Thanks Marc,

Could perhaps have something to do with that I'm using the Composite UI
Application Block... do you happen to know something about it?

Regards,
JOachim
 

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

Back
Top