using System; using System.Windows; using System.Windows.Input; namespace WpfEditor { public partial class FindDialog : Window { private TextEditorControl _textEditor; public FindDialog(TextEditorControl textEditor) { InitializeComponent(); _textEditor = textEditor; // 设置焦点到搜索文本框 SearchTextBox.Focus(); // 添加键盘事件处理 SearchTextBox.KeyDown += SearchTextBox_KeyDown; // 如果编辑器有选中文本,将其作为默认搜索内容 string selectedText = _textEditor.GetSelectedText(); if (!string.IsNullOrEmpty(selectedText)) { SearchTextBox.Text = selectedText; SearchTextBox.SelectAll(); } } private void SearchTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { if (Keyboard.Modifiers == ModifierKeys.Shift) { FindPrevious(); } else { FindNext(); } e.Handled = true; } else if (e.Key == Key.Escape) { Close(); e.Handled = true; } } private void FindNextButton_Click(object sender, RoutedEventArgs e) { FindNext(); } private void FindPreviousButton_Click(object sender, RoutedEventArgs e) { FindPrevious(); } private void CloseButton_Click(object sender, RoutedEventArgs e) { Close(); } private void FindNext() { string searchText = SearchTextBox.Text; if (string.IsNullOrEmpty(searchText)) return; bool matchCase = MatchCaseCheckBox.IsChecked == true; bool wholeWord = WholeWordCheckBox.IsChecked == true; bool found = _textEditor.FindNext(searchText, matchCase, wholeWord); if (!found) { MessageBox.Show("未找到指定的文本。", "查找", MessageBoxButton.OK, MessageBoxImage.Information); } } private void FindPrevious() { string searchText = SearchTextBox.Text; if (string.IsNullOrEmpty(searchText)) return; bool matchCase = MatchCaseCheckBox.IsChecked == true; bool wholeWord = WholeWordCheckBox.IsChecked == true; bool found = _textEditor.FindPrevious(searchText, matchCase, wholeWord); if (!found) { MessageBox.Show("未找到指定的文本。", "查找", MessageBoxButton.OK, MessageBoxImage.Information); } } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textEditor.ClearFindHighlight(); } } }