#718 – Copying Text To and From the Clipboard

You can copy data to or from the Windows clipboard using static methods in the System.Windows.Clipboard class.

Here’s an example that copies text from a TextBox onto the clipboard and pastes text from the clipboard into a Label.

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>

        <TextBox Name="txtFrom" Text="Twas the Night Before Christmas.." Margin="10"/>
        <Button Grid.Column="1" Content="Copy"
                HorizontalAlignment="Left" Padding="10,5" Margin="10"
                Click="btnCopy_Click"/>

        <Label Name="lblTo" Grid.Row="1" Content="Paste something here"
               Margin="10"/>
        <Button Grid.Row="1" Grid.Column="1" Content="Paste"
                VerticalAlignment="Top" HorizontalAlignment="Left"
                Padding="10,5" Margin="10"
                Click="btnPaste_Click"/>
    </Grid>

The Click handlers use the SetText and GetText methods of the Clipboard class to interact with the clipboard.  The SetText method copies data to the clipboard.  The GetText method pastes data from the clipboard.

        private void btnCopy_Click(object sender, RoutedEventArgs e)
        {
            Clipboard.SetText(txtFrom.Text);
        }

        private void btnPaste_Click(object sender, RoutedEventArgs e)
        {
            lblTo.Content = Clipboard.GetText();
        }

718-001

718-002

718-003

718-004

718-005

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

Leave a comment