WPF 实现 鼠标点击 取消 TextBox 光标
原始需求:TextBox 控件光标取消后运行特定功能函数
所遇问题:若无相关事件,则除了点击其他控件等方式外,无法准确取消光标
解决思路:通过捕获 TextBox 控件外鼠标点击或鼠标移动等操作取消光标,并触发 TextBox 的 LostFocus 事件运行目标功能函数
实现代码:下面案例代码是通过捕获鼠标点击的方式进行触发,也可用其他方式~
csharp
// WPF 界面代码
<Window x:Class="WpfApp2.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:WpfApp2"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800" MouseDown="Window_MouseDown">
<Grid>
<Button Content="Button" Click="MyButtonClick" HorizontalAlignment="Left" Margin="285,214,0,0" VerticalAlignment="Top" Width="75"/>
<TextBox x:Name="pathTextBox" HorizontalAlignment="Left" Height="23" Margin="340,275,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="120" LostFocus="Window_LostFocus"/>
</Grid>
</Window>
// 功能实现代码
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MyButtonClick(object sender, RoutedEventArgs e)
{
MessageBox.Show("安装成功 !", "Test", MessageBoxButton.OK, MessageBoxImage.Information);
}
private void Window_LostFocus(object sender, RoutedEventArgs e)
{
if (!pathTextBox.IsFocused && !pathTextBox.IsMouseOver)
{
MessageBox.Show("成功触发 !", "Test", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
private void Window_MouseDown(object sender, MouseButtonEventArgs e)
{
//Keyboard.ClearFocus();//Keyboard.ClearFocus 也可实现清楚焦点,但其会清楚整个页面所有焦点,导致无法触发 pathTextBox 的 LostFocus 事件
if (pathTextBox.IsFocused)
pathTextBox.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
注意:上述代码欲成功捕捉在TextBox控件外的鼠标点击动作,只能在 该代码运行后的界面(MainWindow)中操作,超出此界面范围便无法捕捉!