TextBox複製剪下問題
阿新 • • 發佈:2019-01-29
首先在佈局中新增鍵盤監聽,如下:
<TextBox Keyboard.KeyDown="TextInput_PreviewKeyDown"/>
然後再***.xaml.cs檔案中實現監聽處理規則:
private bool keydown = false; private void TextInput_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { var box = (TextBox)sender; if (!keydown) { keydown = true; if (e.Key == Key.Enter)//點選Enter鍵 { //相關處理事件 } else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.X) {//剪下 var selectedStr = box.SelectedText; if (String.IsNullOrEmpty(selectedStr)) return; try { Dispatcher.Invoke(() => { var selStartIndex = box.SelectionStart; var remainStr = box.Text.Remove(selStartIndex, selectedStr.Length); box.Text = remainStr; box.SelectionStart = selStartIndex; Clipboard.SetDataObject(selectedStr); }); e.Handled = true; } catch (Exception ex) { Console.WriteLine("剪下失敗:" +ex.Message); } } else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control && e.Key == Key.C) {//複製 var selectedStr = box.SelectedText; if (String.IsNullOrEmpty(selectedStr)) return; try { Dispatcher.Invoke(() => { Clipboard.SetDataObject(selectedStr); }); e.Handled = true; } catch (Exception ex) { Console.WriteLine("複製失敗:" + ex.Message); } } keydown = false; } }
注意:有的裝置上使用WPF程式的剪下功能會失敗,原因已經有網友整理,這裡給出網友的解釋說明,有興趣可以研究看看:
https://blog.csdn.net/puncha/article/details/8174374
https://www.cnblogs.com/wliu6V/p/3506675.html?utm_source=tuicool