WIN7下使用.net(C#)监视剪贴板 (转)

最近需要做一个小程序,需要常驻后台,监视剪贴板变化并提取内容, 在网上查了一些资料,先采用SetClipboardViewer方法实现,具体原理可以参考http://www.cnblogs.com/jht/archive/2006/03/20/354088.html,我的程序中使用的是http://code.google.com/p/clipboardviewer/提供的ClipboardChangeNotifier.cs类,比较方便,类代码见附件(在google code中下载或http://www.kuaipan.com.cn/file/id_22823997376823393.htm),使用方法为: 主窗体初始化时:

[csharp] view plain copy print ?
  1. ClipboardChangeNotifier clipChange = new ClipboardChangeNotifier();  
  2. clipChange.ClipboardChanged += new EventHandler(clipChange_ClipboardChanged);  
  3. clipChange.AssignHandle(this.Handle);  
  4. clipChange.Install();  
    ClipboardChangeNotifier clipChange = new ClipboardChangeNotifier();
    clipChange.ClipboardChanged += new EventHandler(clipChange_ClipboardChanged);
    clipChange.AssignHandle(this.Handle);
    clipChange.Install();

主窗体退出时:

[csharp] view plain copy print ?
  1. clipChange.Uninstall();  
    clipChange.Uninstall();

     此程序在XP下运行正常,但是后来在WIN7下使用时遇到了一些问题,经常会在屏幕保护程序或系统休眠后,不再实时监视剪贴板,具体原因不明,后来查了下资料,有人提到SetClipboardViewer函数在Vista以上版本工作并不是很稳定,建议使用AddClipboardFormatListener这个新的API函数,MSDN(http://msdn.microsoft.com/en-us/library/windows/desktop/ms649033%28v=vs.85%29.aspx)上提到该API函数只能用于Vista及以上版本,经测试,程序工作正常
代码比SetClipboardViewer方法简单: 首先声明API函数

[csharp] view plain copy print ?
  1. [DllImport("user32.dll")]  
  2.     public static extern bool AddClipboardFormatListener(IntPtr hwnd);  
  3.   
  4.     [DllImport("user32.dll")]  
  5.     public static extern bool RemoveClipboardFormatListener(IntPtr hwnd);  
  6.   
  7.     private static int WM_CLIPBOARDUPDATE = 0x031D;  
    [DllImport("user32.dll")]
        public static extern bool AddClipboardFormatListener(IntPtr hwnd);

        [DllImport("user32.dll")]
        public static extern bool RemoveClipboardFormatListener(IntPtr hwnd);

        private static int WM_CLIPBOARDUPDATE = 0x031D;

窗体初始化时添加对剪贴板的监视:  

[csharp] view plain copy print ?
  1. AddClipboardFormatListener(this.Handle);  
 AddClipboardFormatListener(this.Handle);

窗体关闭时移除对剪贴板的监视:

[csharp] view plain copy print ?
  1. RemoveClipboardFormatListener(this.Handle);  
  RemoveClipboardFormatListener(this.Handle);

接收到剪贴板更新的消息时,读取剪贴板内容:

[csharp] view plain copy print ?
  1. protected override void DefWndProc(ref Message m)  
  2.     {  
  3.         if (m.Msg == WM_CLIPBOARDUPDATE)  
  4.         {  
  5.             UpdateClipValueList();  
  6.         }  
  7.         else  
  8.         {  
  9.             base.DefWndProc(ref m);  
  10.         }  
  11.     }  

转载于:https://www.cnblogs.com/lorking/p/4054311.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值