简体   繁体   English

如何在WPF应用程序中挂接事件或更改窗口?

[英]How to hook the event or the changing of the windows in a WPF application?

everyone, hope you well. 大家好,祝您一切顺利。 Here is the requirement: I have a C# WPF application, and I would like to track the events in this app. 这是要求:我有一个C#WPF应用程序,我想跟踪此应用程序中的事件。

Not a native speaker, forgive. 不是母语人士,请原谅。 Thank you. 谢谢。

I found a mouse hook on ' https://github.com/justcoding121/Windows-User-Action-Hook ', but it can hook the global events rather the events in the app. 我在' https://github.com/justcoding121/Windows-User-Action-Hook '上找到了一个鼠标钩,但是它可以钩住全局事件,而不是应用程序中的事件。

This hook cannot hook the events in the WPF application. 该挂钩无法挂钩WPF应用程序中的事件。

Two things you need to be aware of before we can get to the answer itself: 在获得答案本身之前,您需要注意两件事:

1) In WPF, everything except the window itself is artificial -- all UI elements are drawn via DirectX and not the operating system (which is why, for example, in WPF you can put a button into another button but in Windows Forms you can't). 1)在WPF中,除了窗口本身之外的所有东西都是人为的-所有UI元素都是通过DirectX而非操作系统绘制的(这就是为什么,例如,在WPF中,您可以将一个按钮放到另一个按钮中,但是在Windows Forms中,您可以')。 So there isn't a way for the operating system to somehow know about mouse events within the app. 因此,操作系统无法通过某种方式了解应用程序中的鼠标事件。

2) Almost all events in WPF are routed -- that means, when a control fires an event, it can actually be handled in multiple places, typically on that control first and then up the tree to and including the window. 2)WPF中几乎所有事件都被路由-这意味着,当一个控件触发一个事件时,它实际上可以在多个地方进行处理,通常在该控件上首先进行处理,然后再将树上移至并包括该窗口。 Controls up (or down) the tree will fire this event even if it is not declared on them (like Click is not declared on a Window, but a window can still indirectly respond to clicks within itself). 即使没有在树上声明声明(例如,未在Window上声明Click,但是窗口仍可以间接响应自身内的单击),控制树的上(或下)将触发此事件。

That out of the way, you can use events either normally (for example, this.MouseMove += MyHandler; in the window constructor or <Window MouseDown="DownHandler" ...> in XAML) or through the routed events syntax (this.AddHandler(Button.ClickEvent, MyHandler); in C# or <Window Button.Click="ClickHandler" ...> in XAML). 顺便说一句,您可以正常使用事件(例如,在窗口构造函数中使用this.MouseMove + = MyHandler;在XAML中使用<Window MouseDown =“ DownHandler” ...>),也可以使用路由事件语法(此方法.AddHandler(Button.ClickEvent,MyHandler);在C#中,或者在XAML中是<Window Button.Click =“ ClickHandler” ...>)。 The latter is usually needed only when you handle an event that is not declared on the element (like Click on a Window). 通常只有在处理未在元素上声明的事件(例如,单击窗口)时才需要后者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM