You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WinUI 3程序中实现系统剪贴板的剪切、复制、粘贴功能

WinUI 3 实现剪切/复制/粘贴按钮与快捷键一致功能

直接使用WinUI内置的ApplicationCommands命令即可,这些命令和系统Ctrl+X/C/V快捷键的行为完全一致,无需自己实现底层逻辑:

代码后台实现(C#)

给按钮的点击事件绑定以下处理函数,自动作用于当前焦点控件:

private void CutButton_Click(object sender, RoutedEventArgs e)
{
    ApplicationCommands.Cut.Execute(null, FocusManager.GetFocusedElement(Window.Current));
}

private void CopyButton_Click(object sender, RoutedEventArgs e)
{
    ApplicationCommands.Copy.Execute(null, FocusManager.GetFocusedElement(Window.Current));
}

private void PasteButton_Click(object sender, RoutedEventArgs e)
{
    ApplicationCommands.Paste.Execute(null, FocusManager.GetFocusedElement(Window.Current));
}

XAML绑定命令实现

更简洁的方式是直接在XAML中绑定内置命令,无需写后台代码:

<Button Content="剪切" Command="ApplicationCommands.Cut" />
<Button Content="复制" Command="ApplicationCommands.Copy" />
<Button Content="粘贴" Command="ApplicationCommands.Paste" />

如果需要指定命令作用的特定控件,可添加CommandTarget属性:

<Button Content="粘贴" Command="ApplicationCommands.Paste" CommandTarget="{Binding ElementName=MyTextBox}" />

说明

  • 这些内置命令会自动适配当前焦点控件的默认行为,比如文本框选中文本时的剪切、无内容时的状态处理等,和键盘快捷键逻辑完全同步。
  • FocusManager.GetFocusedElement确保命令作用在用户当前操作的控件上,和快捷键的作用目标一致。

内容的提问来源于stack exchange,提问作者samgido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:04:52