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 }