Among the many new features coming in Silverlight 4 is clipboard support. A new class named System.Windows.Clipboard provides three static methods for accessing the system clipboard:
- GetText, which retrieves text from the clipboard
- SetText, which places text on the clipboard
- ContainsText, which indicates whether the clipboard currently contains text
In the Silverlight 4 beta, only Unicode text can be retrieved from the clipboard or added to it. Microsoft hasn’t said whether the final release will support additional clipboard formats, but one can always hope.
To demonstrate, I built a sample app that features a Paste button for pasting text from the clipboard into a TextBlock. It uses a DispatcherTimer to enable or disable the Paste button once a second based on the clipboard’s contents (specifically, whether or not the clipboard currently contains Unicode text). Here’s the XAML:
<Grid x:Name=”LayoutRoot”>
<Grid.Background>
<LinearGradientBrush StartPoint=”0.5,0.0″ EndPoint=”0.5,1.0″>
<GradientStop Offset=”0.0″ Color=”Black” />
<GradientStop Offset=”1.0″ Color=”#FF404040″ />
</LinearGradientBrush>
</Grid.Background>
<StackPanel Orientation=”Vertical”>
<Button x:Name=”PasteButton” Width=”100″ Height=”50″ Margin=”32″
Content=”Paste” IsEnabled=”False” Click=”Button_Click” />
<TextBlock x:Name=”Output” Foreground=”White” FontSize=”20″
TextWrapping=”Wrap” HorizontalAlignment=”Center”
VerticalAlignment=”Center” Margin=”32,0,32,32″ />
</StackPanel>
</Grid>
And here’s the code-behind:
public partial class MainPage : UserControl
{
private DispatcherTimer _timer;
public MainPage()
{
InitializeComponent();
_timer = new DispatcherTimer();
_timer.Interval = new TimeSpan(0, 0, 1);
_timer.Tick += new EventHandler(_timer_Tick);
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
PasteButton.IsEnabled = Clipboard.ContainsText();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
Output.Text = Clipboard.GetText();
}
catch (SecurityException ex)
{
MessageBox.Show(ex.Message);
}
}
}
If the application is running in the browser or if it’s running outside the browser without elevated permissions, clicking the Paste button produces the following confirmation dialog:
If the user answers yes, the application is permitted to access the clipboard. Here’s the result when I pasted in the text of the Gettysburg Address:
If the user denies the application clipboard access, then GetText produces a SecurityException. That’s why I wrapped the call to GetText in a try/catch block—just in case. On a positive note, if the user answers yes when asked if the application can access the clipboard, the answer is cached for the duration of the session and the prompt isn’t displayed again.