我看过一些关于此的帖子,但他们不一定能准确回答我的问题。
我有一个父窗口,在它的 LocationChanged
事件中,它会捕获一个子窗口并以“捕捉”的方式移动它。我想找到一个事件并在子表单上设置一个 bool 值,它会说 “如果用户手动移动了我,我将不会重新附加到父表单。”
有没有办法检测是否是用户移动了子窗口,而不是我的父窗口移动了它?
我希望这是有道理的。
最佳答案
假设您使用子窗口的 Owner
属性将父窗口关联到子窗口,我将使用基于事件的方法。
在您的子窗口中创建一个事件,通知监听器将子窗口与其父窗口分离(分离):
public event EventHandler<EventArgs> DetachOwner;
您接下来需要确定何时应该引发此事件。为此,我们将在子窗口中使用三个事件:Activated
、Deactivated
和 LocationChanged
。
LocationChanged
会告诉我们子窗口何时移动,但我们需要过滤掉子窗口移动的情况,因为它跟随父窗口。为此,我们需要知道子 Window 是否在移动并且它有焦点。要跟踪子窗口的焦点状态,请创建一个名为 HasFocus
的 bool 字段,并在窗口的 Activated
事件处理程序中将 HasFocus
设置为 true,将其设置为 false在窗口的 Deactivated
处理程序中。
将此添加到您的子窗口:
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;
}
在父窗口中,当您实例化子窗口时,您将订阅子窗口的 DetachOwner
事件:
_child = new Child();
_child.Owner = this;
// Subscribe to the DetachOwner event.
_child.DetachChild += Child_DetachOwner;
此 DetachOwner
处理程序只是将子窗口的 Owner
属性设置为 null:
void Child_DetachOwner(object sender, EventArgs e) {
((Child)sender).Owner = null;
}
您可以扩展此方法,通过在子窗口中使用父窗口中的处理程序创建类似的 AttachOwner 事件,将子窗口重新附加到其父窗口:
void Child_AttachOwner(object sender, EventArgs e) {
((Child)sender).Owner = this;
}
关于c# - 检测用户是否在 WPF 中移动了窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16432614/