Monitoring Clipboard Activity in C#

Welcome to this week's installment of .NET Tips & Techniques! Each week, award-winning Architect and Lead Programmer Tom Archer demonstrates how to perform a practical .NET programming task using either C# or Managed C++ Extensions.

My MFC book Visual C++ .NET Bible includes a chapter on working with the Windows Clipboard from Visual C++. Quite a number of readers have asked about how to perform similar tasks in C#. One of those tasks—which the "Clipboard ring" in Microsoft Office has made popular—is specifying that your application is notified if the Clipboard changes. This week's installment of .NET Tips & Techniques provides both an overview and a step-by-step example for accomplishing this with .NET and C#. That way, if you're already familiar with how the Clipboard works (or you're in a hurry) and just want to jump directly to the code, you can.

Figure 1: Example of Monitoring the Windows Clipboard for Any RTF or ASCII Text

Overview

Windows maintains a list, or chain, of windows that have requested to be notified when data on the Clipboard has been modified. Each time the Clipboard data is modified, the first window in this chain receives a message—WM_DRAWCLIPBOARD. The window then can query the Clipboard as to the type of data it contains (such as RTF, ASCII text, and so on) and the actual data. Because there is no managed (.NET) API for adding a window to this notification chain, you have to use the Win32 SetClipboardViewer function. While this is a fairly simple process, you should be aware of some general guidelines when using this function.

  • When calling the SetClipboardViewer function, you need to pass the handle of the window that will receive the WM_DRAWCLIPBOARD message. The SetClipboardViewer function returns the current first window in the chain. Your application should store this value—typically in a class member—because each window that receives the WM_DRAWCLIPBOARD message has to send that same message to the next window in the chain (via the SendMessage function).
  • Handle the WM_DRAWCLIPBOARD message. This can be done by providing a Form class overload of the WndProc method. You'll see an example of doing this shortly.
  • Handle WM_CHANGECBCHAIN message. Because each window that handles the WM_DRAWCLIPBOARD message is responsible for sending that message to the next window in the chain, it must also know when the chain changes. The Clipboard sends the WM_CHANGECBCHAIN message when a window has removed itself from the chain.
  • Remove the window from the chain when finished. This task is accomplished via the Win32 ChangeClipboardChain function, and it can be done any time that Clipboard monitoring is no longer needed.

Step-by-step Instructions

  1. As mentioned in the Overview, you'll need to call several Win32 functions—SetClipboardViewer, ChangeClipboardChain, and SendMessage—in your application. In order to do that from a .NET application, you first have to import those functions by using the DllImport attribute (which resides in the System.Runtime.InteropServices namespace). The following example imports these functions within the demo application's Form class:
  2. using System.Runtime.InteropServices;
    ...
    public class Form1 : System.Windows.Forms.Form
    {
      [DllImport("User32.dll")]
      protected static extern int
                SetClipboardViewer(int hWndNewViewer);
    
      [DllImport("User32.dll", CharSet=CharSet.Auto)]
      public static extern bool
             ChangeClipboardChain(IntPtr hWndRemove,
                                  IntPtr hWndNewNext);
    
      [DllImport("user32.dll", CharSet=CharSet.Auto)]
      public static extern int SendMessage(IntPtr hwnd, int wMsg,
                                           IntPtr wParam,
                                           IntPtr lParam);
      ...
    
  3. Define a class member to hold the current first window in the Clipboard notification chain:
  4. public class Form1 : System.Windows.Forms.Form
    {
      ...
      IntPtr nextClipboardViewer;
    
  5. Call the SetClipboardViewer function. In the demo, I call this function in the form's constructor:
  6. public Form1()
    {
      InitializeComponent();
      nextClipboardViewer = (IntPtr)SetClipboardViewer((int)
                             this.Handle);
      ..
    
  7. Within the Form class, override the WndProc method. As you can see here, I handle only two messages: WM_DRAWCLIPBOARD and WM_CHANGECBCHAIN. Note that I define two constants for these messages (where both values can be found in the Platform SDK's winuser.h file.)

    In the WM_DRAWCLIPBOARD message-handling code, I call a helper function to display the text that is currently on the Clipboard and pass the same message on to the next window in the chain. (You can see the code to display RTF and ASCII text in the article's demo code at the end of this column.)

    In the WM_CHANGECBCHAIN message-handling code, I check to see whether the window being removed from the Clipboard chain (passed in the Message.WParam member) is the next window in the chain. If it is, I then set the form's next window member variable (nextClipboardViewer) to the next window in the chain (passed in the Message.LParam member):

    protected override void
              WndProc(ref System.Windows.Forms.Message m)
    {
      // defined in winuser.h
      const int WM_DRAWCLIPBOARD = 0x308;
      const int WM_CHANGECBCHAIN = 0x030D;
    
      switch(m.Msg)
      {
        case WM_DRAWCLIPBOARD:
          DisplayClipboardData();
          SendMessage(nextClipboardViewer, m.Msg, m.WParam,
                      m.LParam);
        break;
    
        case WM_CHANGECBCHAIN:
          if (m.WParam == nextClipboardViewer)
            nextClipboardViewer = m.LParam;
          else
            SendMessage(nextClipboardViewer, m.Msg, m.WParam,
                        m.LParam);
        break;
    
        default:
          base.WndProc(ref m);
        break;
      }
    }
    
  8. Finally, I remove the window from the Clipboard chain when the window class's Dispose method is called by the .NET runtime:
  9. protected override void Dispose( bool disposing )
    {
      ChangeClipboardChain(this.Handle, nextClipboardViewer);
      ...
    

A Chain Is Only As Strong...

After following these few steps, your application will be notified of any changes to the text on the Clipboard. Like a lot of tasks in Windows development, it's not very difficult once you know the right APIs to call. The key issue with working with the Clipboard is to make sure that you follow a few simple rules so that other applications in the Clipboard chain continue to perform correctly.



About the Author

Tom Archer - MSFT

I am a Program Manager and Content Strategist for the Microsoft MSDN Online team managing the Windows Vista and Visual C++ developer centers. Before being employed at Microsoft, I was awarded MVP status for the Visual C++ product. A 20+ year veteran of programming with various languages - C++, C, Assembler, RPG III/400, PL/I, etc. - I've also written many technical books (Inside C#, Extending MFC Applications with the .NET Framework, Visual C++.NET Bible, etc.) and 100+ online articles.

Downloads

Comments

  • Beats krijgt de muziek voor u door Dr Dre

    Posted by mrswanzi on 06/05/2013 11:00pm

    [url=http://koptelefoon-monsterbeats.webs.com/]beats by dre[/url] Met de Monstercable Beats Dr. Dr¨¦ gaat u op in de muziek terwijl u vergeet dat u een hoofdtelefoon draagt. De oorschelpen zijn groot en comfortabel dankzij soepele kussentjes van zacht en geventileerd materiaal. De Beats hoofdtelefoon heeft bovendien een glanzend design en is krasbestendig. [url=http://koptelefoon-monsterbeats.tumblr.com/]beats by dre[/url] Tijdens de afgelopen Olympische Spelen werd de populariteit van de Monster Beats by Dr. Dre hoofdtelefoons weer aangetoond. Zelfs een waarschuwing van het IOC, het Internationaal Olympisch Comit¨¦, kon niet voorkomen dat diverse sporters voor hun wedstrijden te zien waren met een Beats by Dr. Dre op het hoofd. Want hoe komen deze koptelefoons aan de ongekende populariteit De Beats by Dr. Dre hoofdtelefoons zijn hot. Heel erg hot. Loop buiten een rondje en de kans is meer dan groot dat je tijdens dat rondje minstens ¨¦¨¦n exemplaar tegen komt. Achter de opkomst van deze hype zit een goed uitgedachte strategie. Want hoe komen deze koptelefoons aan de ongekende populariteit [url=http://koptelefoon-monsterbeats.tumblr.com/]Goedkope Dr Dre Beats [/url] Met de urBeats van Monster Beats by Dr Dre gaat er een wereld van geluid voor je open. Klein van stuk, maar groots van geluid! Heeft u genoeg van het steeds vervangen van die in-ears Maak daar dan voor eens en voor altijd korte mette mee en haal de Beats in huis, en u hoort wat u al die tijd hebt gemist. Ze zijn zo gemaakt dat u al het buitengewone HD-audio materiaal van uw iPod, iPad of iPhone weer kunt horen. Het is ongelooflijk wat voor geweldig geluid er uit zo'n klein oortelefoontje kan komen. Als u eenmaal over de Beats beschikt wilt u nooit meer anders!

    Reply
  • auriculares beats de dr. dre saben que usted puede ver fcilmente la gente

    Posted by cheneason on 06/03/2013 11:09pm

    [url=http://www.beats-studio1.webnode.fr/]auriculares Studio Beats[/url] One caveat: The Zoro does not hold up well to repeated high volume usage on deep bass tracks that cause distortion. As with many pairs in the $100-range, this eventually seems to lead to some permanent driver damage. It doesn’t mean the headphones will be unusable, but they might suffer from a bit of rattling or fuzziness on certain frequencies, regardless of the volume—at the end of our testing, a third deep bass, high volume test ended up doing some damage to the right ear’s drivers. [url=http://www.comprarbeatsbaratos.weebly.com/]Comprar beats baratos[/url] DRE beat, begrebet glatte jazz, klassiske elementer blandet rock, elektronisk musik, skaber fantastiske beats by dre unik lyd. Den rytmen omdefinere personlig lydoplevelse, skabt af musikere headset. Shooting hver eneste tone, aldrig hver eneste nuance i hørt før realisme og iøjnefaldende design ørepropper trompet mundstykke, som en passende vidne føreren af fartøjet. Det er ikke kun de bedste hovedtelefoner til jazz. Uanset om du lytter, vil rytmen være et nyt højdepunkt for al din musik. [url=http://www.beatsbydrdrebaratos.weebly.com/]auriculares beats[/url] Udover alle andre hovedtelefoner par, beats Dre lyd præsentation er temmelig god, ikke som “mudrede” og “uklar” støjende lyde, som ofte er problemer med hver hovedtelefon. Nå, denne genre af hovedtelefon er meget godt for den elektroniske, hård rock, og midt tempo hip-hop musik, som helt sikkert kan rock you ingen tvivl om. billige beats by dre er meget til salg i forskellige musik-butikker og du kan købe dem fra enhver stikkontakt til pluk det til din musik dille. Nå, ingen tvivl om, at du kan have en god musik ved at have det, efter alt dette er ‘beats by Dre «og navnet i sig selv er alt for at angive dets kvalitet. Så ven, så hvis du er en af dem, der søger for at have hovedtelefoner til dit musiksystem eller spekulerer at købe det til din iPhone eller iPod, kan du placere din ordre online. Du kan købe denne genre af hovedtelefoner lige fra sidder fra din hjemmecomputer, logge på hjemmesiden at udforske Dre beats rækkevidde at smage essensen af musikken.

    Reply
  • Nike Air Max 1 FB liberating, have on the agenda c trick a piquant color texture, the brand-new shoes

    Posted by Geozyoceada on 04/23/2013 09:34pm

    In the summer in a pane guts the cool sprite seems to be a good fitting, but if the sprite "feet"? Inclination also disclose you a frisk, get a refreshing! This summer, Nike and Sprite [url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] and his sneakers to a commingling of enduring snow spread of green, drained and blue color scheme in the time-honoured Nike Feeling Max 1 shoes romp a food cool scent.[url=http://fossilsdirect.co.uk/glossarey.cfm]nike huarache[/url] Summer is the metre to pick a cleanly shoe, shoes should be a good choice. Qualifying series Nike Publicize Max HomeTurf borough recently at the end of the day comes up, this series in the immortal Air Max shoes to London, Paris and Milan the three paid eulogy to the iconic metropolis of Europe, combined with the characteristics of the three cities, Sense Max 1 HYP,Air Max 90 HYP,Show Max 1 and shoes such as Air Max 95, combined [url=http://markwarren.org.uk/property-waet.cfm]air max 90 uk[/url] with the Hyperfuse, as kindly as a collection of materials, such as suede, Whether you hankering functional or retro-everything.

    Reply
  • Jordan shoes mentioned Gene to buy the manufacturer, a segment of Nike

    Posted by TaddyGaffic on 04/20/2013 01:57pm

    In focus groups conducted at 80 community-based organizations around the country, Motivational Educational Entertainment of Philadelphia [url=http://markwarren.org.uk/goodbuy.cfm]nike free[/url] identified disturbing trends among youths ages 16 to 20. The "Just Say No" message of abstinence-only campaigns has been lost on this group of young people, who grew up during an era when the hip-hop sensibility of getting cash and clothes did not incorporate values of conscientious sexual behavior or social responsibility. Rappers who mingle [url=http://northernroofing.co.uk/roofins.cfm]nike free run 3[/url] with glamorous-looking half-naked women rarely mention contraception while they're listing the number of compromising sexual situations they've been in lately. There are number of good brands in the market like Adidas, Nike, Reebok, Asics, Brooks, Puma etc. Most of these brands have shoes tailored for professional and amateur tennis players. New advanced technologies have made these shoes more player-friendly. After that, I eventually like to try to get down to the 150-160 range. I not entirely sure if that a healthy number for a gal my height or not, and I haven looked into it. But, I know that when I was 180 I still didn feel that [url=http://markwarren.org.uk/goodbuy.cfm]nike free run[/url] fit, so I think an extra 20 or so will help with that.. Lotto sneakers selling price are generally liable along with using the form of sneakers you choose on. Your Lotto sneakers established fact because of their style along with good quality plus the create. That they create sneakers coming from all varieties much like the loafers,Puma II Shoes, new sandals, sneakers along with task tennis shoes or anything else

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • With JRebel, developers get to see their code changes immediately, fine-tune their code with incremental changes, debug, explore and deploy their code with ease (both locally and remotely), and ultimately spend more time coding instead of waiting for the dreaded application redeploy to finish. Every time a developer tests a code change it takes minutes to build and deploy the application. JRebel keeps the app server running at all times, so testing is instantaneous and interactive.

  • Instead of only managing projects organizations do need to manage value! "Doing the right things" and "doing things right" are the essential ingredients for successful software and systems delivery. Unfortunately, with distributed delivery spanning multiple disciplines, geographies and time zones, many organizations struggle with teams working in silos, broken lines of communication, lack of collaboration, inadequate traceability, and poor project visibility. This often results in organizations "doing the …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds