如何捕获和处理PreviewMouseDownOutsideCapturedElementEvent?

时间:2015-05-26 14:07:40

标签: c# wpf mouseevent

我有一个带有边框的干净窗口,我想要处理MouseClick,如果它是那个边框 我试过这段代码,但它没有用:

enter image description here

代码背后:

  public MainWindow()
    {
        InitializeComponent();
        AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler(onmousedown), true);
        Mouse.Capture(this.border,CaptureMode.Element);

    }

    private void onmousedown(object sender, MouseButtonEventArgs e)
    {
        MessageBox.Show("Test");
    }

请帮助我,或指导我如何做到这一点。

2 个答案:

答案 0 :(得分:2)

我通过创建一个简单的控件来解决我的问题,如下所示: 我得到的是在load事件中初始化捕获。

 public class ModulesMenuControl : Control
    {          
 static ModulesMenuControl()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(ModulesMenuControl), new FrameworkPropertyMetadata(typeof(ModulesMenuControl)));
        }

        public ModulesMenuControl()
        {
            this.Loaded += MouseCaptureControl_Loaded;
        }

        void MouseCaptureControl_Loaded(object sender, RoutedEventArgs e)
        {
            //throw new NotImplementedException();
            this.AddHandler(Mouse.PreviewMouseDownOutsideCapturedElementEvent, new MouseButtonEventHandler(onmousedown), true);
            Mouse.Capture(this, CaptureMode.SubTree);
        }

        private void onmousedown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("out click");
        }

答案 1 :(得分:1)

MouseDown事件添加到Window(或父控件),您可以使用MouseButtonEventArgs来确定单击了哪个元素。这是一个例子:

<Grid Background="Transparent" MouseDown="GridMouseDown">
    <Border Width="100" Height="100" Background="Red"/>
</Grid>

在你的C#代码中:

private void GridMouseDown(object sender, MouseButtonEventArgs e)
{
    //use e.Source to check which element was clicked, like this:
    if (e.Source.GetType() == typeof(Border))
    {
        MessageBox.Show("The border was clicked");
    }

    //Or, you can check the name of the element, like this:
    if (((FrameworkElement)e.Source).Name == "myBorderName")
    {
        //Something useful.
    }
}