Reputation: 5007
I have seen a couple posts on this, but they don't necessarily answer my question exactly.
I have a parent window that on its LocationChanged
event, it will grab a child window and move that along with it in a "snapped" fashion. I want to find an event and set a boolean value on the child form that would say "if the user has manually moved me, I will not re-attach to the parent."
Is there a way to detect if the user has moved the child window, rather than my parent window moving it?
I hope this makes sense.
Upvotes: 3
Views: 5791
Reputation: 53603
Assuming you are using your child Window's Owner
property to associate your parent Window to the child Window I would use an events-based approach.
In your child Window create an event that notifies listeners to disassociate (detach) the child Window from its parent:
public event EventHandler<EventArgs> DetachOwner;
You next need to determine when this event should be raised. For this we'll use three events in the child Window: Activated
, Deactivated
and LocationChanged
.
LocationChanged
will tell us when the child Window has moved but we'll need to filter out cases when the child Windows moves because it's following the parent Window. To do this we will need to know if the child Window is moving and it has focus. To track the focus state of the child Window create a bool field called HasFocus
and set HasFocus
to true in the Window's Activated
event handler, and false in the Window's Deactivated
handler.
Add this to your child Window:
private void Window_LocationChanged(object sender, EventArgs e) {
if (HasFocus) {
if (DetachChild != null) {
DetachChild(this, EventArgs.Empty);
}
}
}
bool HasFocus;
private void Window_Activated(object sender, EventArgs e) {
HasFocus = true;
}
private void Window_Deactivated(object sender, EventArgs e) {
HasFocus = false;
}
In the parent Window you'll subscribe to the child Window's DetachOwner
event when you instantiate the child Window:
_child = new Child();
_child.Owner = this;
// Subscribe to the DetachOwner event.
_child.DetachChild += Child_DetachOwner;
This DetachOwner
handler simply sets the child Window's Owner
property to null:
void Child_DetachOwner(object sender, EventArgs e) {
((Child)sender).Owner = null;
}
You can expand on this approach to reattach the child Window to it's parent by creating a similar AttachOwner event in the child Window with a handler in the parent Window:
void Child_AttachOwner(object sender, EventArgs e) {
((Child)sender).Owner = this;
}
Upvotes: 6