2016-08-11 71 views
0

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

<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 

     } 
    } 
} 

回答

0

您可以使用Mouse.GetPosition获得相对于按钮的角落光标位置,位置比较按钮的ActualHeight

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

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

当在按钮内部抬起鼠标按钮时触发鼠标上升,而在按钮内按下时鼠标按下(您能猜到?)。

编辑:我刚才检查的MouseDown的细节,你将不得不使用

Point p = e.GetPosition(yourButton); 

获得鼠标相对于按钮的位置(您可以通过任何控制代替yourButton让鼠标相对于它的位置)

0

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

然后,您可以对其点击处理程序进行编程,以完成您想要的操作,甚至可以激活底层可见按钮的点击处理程序(如果您愿意的话)。

+0

我不知道这是一个干净的方式来做到这一点.... –

+0

为什么不呢? OP在单击GUI上的某个区域时需要特殊功能。这听起来像一个按钮的工作。 – user2647513

+0

我可能会工作,但如果你可以做到这一点,而无需添加新的(隐藏的)UI元素,对我来说它更清洁 –

0

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

除了提供的答案,我认为这是正确的,你也可以玩弄布局。例如,你可以定义一个边界,包含两个按钮,其中用户会认为,只有一个按钮:

<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> 

通过从你所述的在风格的按钮删除边框,你有这样的事情:

enter image description here

您还可以设置边框的背景颜色,当用户将鼠标悬停其鼠标放在它,使用的MouseEnter和鼠标离开事件。

无论如何,当用户点击这个秘密区域按钮,你可以简单地处理该事件:

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