Search code examples
windowswindows-runtimewinui-3

How can I use the system's clipboard in a winui 3 program


I have buttons for cut, copy and paste. I literally need them to do the exact same thing as their respective keyboard shortcuts would do.

Is there any function that I can stick into an event handler for these buttons to make this work?


Solution

  • Let me show you a simple example using the Windows.ApplicationModel.DataTransfer.Clipboard class:

    <StackPanel
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        Orientation="Horizontal">
        <TextBox />
        <TextBox />
        <TextBox />
        <Button
            x:Name="CutButton"
            Click="CutButton_Click"
            Content="Cut" />
        <Button
            x:Name="CopyButton"
            Click="CopyButton_Click"
            Content="Copy" />
        <Button
            x:Name="PasteButton"
            Click="PasteButton_Click"
            Content="Paste" />
        <TextBox x:Name="PasteTextBox" />
    </StackPanel>
    
    
    public MainPage()
    {
        this.InitializeComponent();
        FocusManager.GotFocus += FocusManager_GotFocus;
    }
    
    private void FocusManager_GotFocus(object? sender, FocusManagerGotFocusEventArgs e)
    {
        if (e.NewFocusedElement is TextBox textBox)
        {
            _previousFocusedTextBox = textBox;
        }
    }
    
    private void CutButton_Click(object sender, RoutedEventArgs e)
    {
        DataPackage dataPackage = new();
        dataPackage.RequestedOperation = DataPackageOperation.Move;
        dataPackage.SetText(_previousFocusedTextBox.Text);
        Clipboard.SetContent(dataPackage);
        _previousFocusedTextBox.Text = string.Empty;
    }
    
    private void CopyButton_Click(object sender, RoutedEventArgs e)
    {
        DataPackage dataPackage = new();
        dataPackage.RequestedOperation = DataPackageOperation.Copy;
        dataPackage.SetText(_previousFocusedTextBox.Text);
        Clipboard.SetContent(dataPackage);
    }
    
    private async void PasteButton_Click(object sender, RoutedEventArgs e)
    {
        DataPackageView dataPackageView = Clipboard.GetContent();
    
        if (dataPackageView.Contains(StandardDataFormats.Text) is true)
        {
            this.PasteTextBox.Text = await dataPackageView.GetTextAsync();
        }
    }