C++简单剪贴板操作
1 class ClipboardExample 2 { 3 public: 4 ClipboardExample(); 5 ~ClipboardExample(); 6 7 BOOL SetClipData(char *pstr); 8 char* GetClipData(); 9 char* GetError(); 10 private: 11 DWORD errCode; 12 HGLOBAL hClip; 13 };
1 ClipboardExample::ClipboardExample() 2 { 3 errCode=0; 4 hClip=NULL; 5 } 6 7 ClipboardExample::~ClipboardExample() 8 { 9 if(hClip) 10 CloseHandle(hClip); 11 } 12 13 BOOL ClipboardExample::SetClipData(char *pstr) 14 { 15 if(OpenClipboard(NULL)) 16 { 17 char *pBuf; 18 if(0==EmptyClipboard()) 19 { 20 CloseClipboard(); 21 return false; 22 } 23 hClip=GlobalAlloc(GMEM_MOVEABLE,strlen(pstr)+1); 24 if(NULL==hClip) 25 { 26 CloseClipboard(); 27 return false; 28 } 29 pBuf=(char*)GlobalLock(hClip); 30 if(NULL==pBuf) 31 { 32 CloseClipboard(); 33 return false; 34 } 35 strcpy(pBuf,pstr); 36 GlobalUnlock(hClip); 37 38 if(NULL==SetClipboardData(CF_TEXT,hClip)) 39 { 40 CloseClipboard(); 41 return false; 42 } 43 44 CloseClipboard(); 45 } 46 return true; 47 } 48 49 char* ClipboardExample::GetClipData() 50 { 51 char* pstr=0; 52 if(OpenClipboard(NULL)) 53 { 54 if(IsClipboardFormatAvailable(CF_TEXT)) 55 { 56 hClip = GetClipboardData(CF_TEXT); 57 if(NULL==hClip) 58 { 59 CloseClipboard(); 60 return false; 61 } 62 pstr = (char*)GlobalLock(hClip); 63 GlobalUnlock(hClip); 64 CloseClipboard(); 65 } 66 } 67 return pstr; 68 } 69 70 char* ClipboardExample::GetError() 71 { 72 errCode = GetLastError(); 73 char pstr[128]; 74 itoa(errCode,pstr,10); 75 return pstr; 76 }
1 #include <Windows.h> 2 #include <iostream> 3 #include <stdio.h> 4 #include "ClipboardExample.h" 5 using namespace std; 6 7 8 void main() 9 { 10 ClipboardExample clip = ClipboardExample(); 11 while(1) 12 { 13 cout<<"************************"<<endl; 14 cout<<"***********菜单*********"<<endl; 15 cout<<"**[1]setCli,[2]getClip**"<<endl; 16 cout<<"*******[q]退出程序******"<<endl; 17 cout<<"************************"<<endl; 18 char buf[128]; 19 char* pstr=0; 20 cout<<":"<<flush; 21 gets(buf); 22 switch(buf[0]) 23 { 24 case '1': 25 cout<<"输入要设置的数据:"<<flush; 26 gets(buf); 27 if(!clip.SetClipData(buf)) 28 { 29 cout<<"设置剪贴板数据失败,错误代码:"<<clip.GetError()<<endl; 30 } 31 else 32 { 33 cout<<"设置剪贴板数据成功"<<endl; 34 } 35 break; 36 case '2': 37 pstr=clip.GetClipData(); 38 if(!pstr) 39 { 40 cout<<"获取剪贴板数据失败,错误代码:"<<clip.GetError()<<endl; 41 } 42 else 43 { 44 cout<<"获取剪贴板数据成功,data="<<pstr<<endl; 45 } 46 break; 47 case 'q': 48 cout<<"see you later!"<<endl; 49 system("pause"); 50 return; 51 default: 52 cout<<"输入有误,请重新输入!"<<endl; 53 break; 54 } 55 } 56 }
欢迎 C++/Python 的朋友一起交流学习, My QQ Number: 2303186535
-- 来自m星人的问候