繁体   English   中英

仅当用户ctrl单击按钮的下半部分时才如何触发事件?

[英]How to trigger an event only when the user ctrl click the lower half of a button?

我想在我的应用程序中实现一些秘密功能,并且只能通过ctrl左键单击按钮的下半部分来调用它们。 这可以在WPF中实现吗? 我尝试创建一个演示应用程序,并且调试未在click事件处理程序中向我显示光标位置信息。 下面是我的测试代码。 有任何想法吗?

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="255.284" Width="313.918">
    <Grid>
        <Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="81,89,0,0" VerticalAlignment="Top" Width="158" Height="49" Click="button_Click"/>
    </Grid>
</Window>
using System.Windows;

namespace WpfApplication1
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        { // <----- set break point here, can't find cursor info in e and sender

        }
    }
}

您可以使用MouseUp或MouseDown事件,这两个事件都可以为您提供事件参数中的鼠标位置以及按下的鼠标按钮。

当在按钮内部将鼠标按钮抬起时,将触发鼠标上移;在按钮内部被按下时,按下鼠标将触发(您能猜到吗?)。

编辑:我只是检查了MouseDown的详细信息,您将不得不使用

Point p = e.GetPosition(yourButton);

获取鼠标相对于按钮的位置(您可以用任何控件替换yourButton以获得鼠标相对于按钮的位置)

有很多方法可以做到这一点!

除了提供的答案(我认为是正确的)之外,您还可以尝试布局。 例如,您可以定义一个边框,其中包含两个按钮,用户会认为其中只有一个按钮:

<Grid HorizontalAlignment="Center" VerticalAlignment="Center" Width="250" Height="100" >
    <Border BorderBrush="Black" BorderThickness="1" MouseEnter="border_MouseEnter" MouseLeave="border_MouseLeave">
        <StackPanel>
            <Button  VerticalAlignment="Top" Height="50" Style="{StaticResource ButtonStyle}" Content="MainButton"></Button>
            <Button  VerticalAlignment="Bottom" Content="SecretArea" Style="{StaticResource ButtonStyle}" Height="50" Click="Button_Click"></Button>
        </StackPanel>
    </Border>
</Grid>

通过以您定义的样式从按钮上删除边框,您将获得以下内容:

在此处输入图片说明

您还可以使用MouseEnter和MouseLeave事件,在用户将鼠标悬停在边框上时设置边框的背景颜色。

无论如何,当用户单击秘密区域按钮时,您可以简单地处理事件:

private void Button_Click(object sender, RoutedEventArgs e)
{
      MessageBox.Show("Secret Area");
}

您可以使用Mouse.GetPosition来获取相对于按钮角的光标位置,并将该位置与按钮的ActualHeight进行比较:

var pos = Mouse.GetPosition(button);
if(pos.Y >= button.ActualHeight * 0.5)
{
    //do something
}

在现有按钮的下半部分上方添加第二个按钮,但将其设置为对用户不可见。

然后,您可以对其点击处理程序进行编程,以完全按照您的要求进行操作,甚至可以根据需要激活底层可见按钮的点击处理程序。

暂无
暂无

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

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