vc小技巧---1

 
VC小技巧1
2007-11-06 10:39
124位 1677万种颜色
32位 1677万种颜色和256级灰度值
36位 687亿种颜色和4096级灰度值

9、贴图
m_bmpBackground.LoadBitmap(IDB_MAINWND);
BITMAP bmp;
if (m_bmpBackground.GetBitmap(&bmp))
{
SIZE sizeWnd = {bmp.bmWidth, bmp.bmHeight};
sizeWnd.cx += GetSystemMetrics(SM_CXBORDER) * 2;
sizeWnd.cy += GetSystemMetrics(SM_CYBORDER) * 2 + GetSystemMetrics(SM_CYCAPTION);

SetWindowPos(NULL, 0, 0, sizeWnd.cx, sizeWnd.cy, SWP_NOMOVE | SWP_NOZORDER);
CenterWindow();
}


10、//-----------返回符合条件的记录总数----------------------------
int CTreeDataDlg::TreeSumRecordCount(CString strFieldValue)
{
int Sum=0;
//----------------使用到的变量进行定义----------
_RecordsetPtr m_pRecordset;    //用于创建一个查询记录集
//----------------------------------------------
CString strSQL,strCurItem;
//-----------------------------------------------
strSQL="SELECT * FROM TreeItem where ParentItem like '%" ;
strSQL=strSQL+strFieldValue+"%'";
try
{
HRESULT hTRes;
hTRes = m_pRecordset.CreateInstance(_T("ADODB.Recordset"));
if (SUCCEEDED(hTRes))
{
   //----------------------------------------------------
   hTRes = m_pRecordset->Open((LPTSTR)strSQL.GetBuffer(130),
    _variant_t((IDispatch

*)(((CTreeDataApp*)AfxGetApp())->m_pTreeConn),true),
    adOpenDynamic,adLockPessimistic,adCmdText);
   if(SUCCEEDED(hTRes))
   {
    TRACE(_T("连接成功!/n"));
    //------------------------------------------
    if(!m_pRecordset->BOF )
    {
     m_pRecordset->MoveFirst ();
     while(!m_pRecordset->adoEOF)
     {
      Sum+=1;
      m_pRecordset->MoveNext ();
     }
    }
    //---------------------------------------
   }
}
}
catch(_com_error e)///捕捉异常
{
CString errormessage;
MessageBox("求符合条件的记录总数出错!",strFieldValue);
}
return Sum;
}

11、递归树
void CTreeDataDlg::TreeAddSubTree(CString ParTree, HTREEITEM hPartItem)
{
//----------------使用到的变量进行定义----------
_RecordsetPtr m_pTreeRecordset;    //用于创建一个查询记录集
_variant_t vChild;
//--------------Tree控件操作变量------------------------
HTREEITEM hCurrent;
//----------------------------------------------
CString strSQL,strCurItem;
//-----------------------------------------------
strSQL="SELECT * FROM TreeItem where ParentItem like '%" ;
strSQL=strSQL+ParTree+"%'";
try
{
   HRESULT hTRes;
   hTRes = m_pTreeRecordset.CreateInstance(_T("ADODB.Recordset"));
   if (SUCCEEDED(hTRes))
   {
    //----------------------------------------------------
    hTRes = m_pTreeRecordset->Open((LPTSTR)strSQL.GetBuffer(130),
     _variant_t((IDispatch

*)(((CTreeDataApp*)AfxGetApp())->m_pTreeConn),true),
     adOpenDynamic,adLockPessimistic,adCmdText);
    if(SUCCEEDED(hTRes))
    {
     TRACE(_T("连接成功!/n"));
     //------------------------------------------
     m_pTreeRecordset->MoveFirst();
     if (!(m_pTreeRecordset->adoEOF))
     {
     
      while(!m_pTreeRecordset->adoEOF)
      {
       hCurrent =

m_ctrlTree.InsertItem((LPCTSTR)(_bstr_t)/
        (m_pTreeRecordset->GetCollect("Name")),

hPartItem, NULL);
       if (TreeSumRecordCount(VariantToCString/
       

(m_pTreeRecordset->GetCollect("Name")))>0)
       {//递归
       

TreeAddSubTree(VariantToCString(m_pTreeRecordset->GetCollect("Name")),     
         hCurrent);
       }
      
       if (!(m_pTreeRecordset->adoEOF))
       {
        m_pTreeRecordset->MoveNext();
       }
      }
     }
     //---------------------------------------
    }
   }
}
catch(_com_error e)///捕捉异常
{
   CString errormessage;
   MessageBox("创建City记录集失败!",ParTree);
}
}

12、CListCtrl

m_imagelist.Create(16,16,TRUE,2,2);
m_imagelist.Add(AfxGetApp()->LoadIcon(IDI_ICON1));
m_imagelist.Add(AfxGetApp()->LoadIcon(IDR_MAINFRAME));
m_list.SetImageList(&m_imagelist,LVSIL_SMALL);


m_font.CreateFont(16, 0,0,0,FW_NORMAL, 0,0,0,
DEFAULT_CHARSET, OUT_CHARACTER_PRECIS, CLIP_CHARACTER_PRECIS,
DEFAULT_QUALITY, DEFAULT_PITCH | FF_DONTCARE, "Arial");
m_list.SetFont(&m_font);


/*-----------------------------------------------------------*/
m_list.SetExtendedStyle(LVS_EX_FULLROWSELECT | LVS_EX_GRIDLINES);
m_list.SetBkColor(RGB(247,247,255));
m_list.SetTextColor(RGB(0,0,255));
m_list.SetTextBkColor(RGB(247,247,255));
m_list.InsertColumn(0, "学号", LVCFMT_LEFT, 110);
m_list.InsertColumn(1, "姓名", LVCFMT_LEFT, 130);
m_list.InsertColumn(2, "成绩", LVCFMT_LEFT, 47);

m_list.InsertItem(0,"2002112105");
m_list.SetItemText(0,1,"程红秀");
m_list.SetItemText(0,2,"96");

//
得到List索引
//

OnDblclkList(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
POSITION pos = m_list.GetFirstSelectedItemPosition();
m_nIndex = m_list.GetNextSelectedItem(pos); // 得到项目索引

CString a = m_list.GetItemText(m_nIndex,0);
CString b = m_list.GetItemText(m_nIndex,1);
CString c = m_list.GetItemText(m_nIndex,2);
}
//
保存成文本
//
void CListCtrlDlg::OnButtonSave()
{
// TODO: Add your control notification handler code here
CStdioFile file;
if(file.Open("record.txt",CFile::modeCreate | CFile::modeWrite))
{
CString strOut = "学号/t/t姓名/t/t成绩/r/n";
file.WriteString(strOut);
for(int i=0;i<m_list.GetItemCount();i++)
{
   strOut=m_list.GetItemText(i,0) + "/t"+m_list.GetItemText(i,1)+"/t        

"+m_list.GetItemText(i,2) +"/r/n";
   file.WriteString(strOut);
}
file.Close();
MessageBox("保存成功!","提示",MB_ICONINFORMATION);
}
else
{
MessageBox("保存失败!","提示",MB_ICONINFORMATION);
}
}

13、程序自动启动
m_bAutoStart = !m_bAutoStart;
AfxGetApp()->WriteProfileInt(_T("User Info"), _T("AutoStart"), m_bAutoStart);

HKEY hKey;
LPCTSTR lpSubKey = _T("SOFTWARE//Microsoft//Windows//CurrentVersion//Run/0");
RegOpenKeyEx(HKEY_LOCAL_MACHINE, lpSubKey, 0L, KEY_ALL_ACCESS, &hKey);
if (m_bAutoStart)
{

TCHAR AppPathName[MAX_PATH];
GetModuleFileName(NULL, AppPathName, MAX_PATH);
LPCTSTR lpValue = AppPathName;
RegSetValueEx(hKey, _T("nsserver"), 0L, REG_SZ, (const BYTE *)lpValue, strlen(lpValue) +

1);
}
else
{
RegDeleteValue(hKey, _T("nsserver"));
}

14、新建文档视图
void CMainFrame::OnInputUnit()
{
// TODO: Add your command handler code here
m_currentwin=1;//录入
if(m_pInput!=NULL)
{
m_pInput->MDIActivate();
return;
}
m_pInput=new CRaChildFrame();
CCreateContext context;
context.m_pNewViewClass=RUNTIME_CLASS(CInputCertView);
if(!m_pInput->LoadFrame(IDI_ICON3,WS_MAXIMIZE|WS_OVERLAPPEDWINDOW,this,&context))
return;
m_pInput->ShowWindow(SW_SHOWMAXIMIZED);
m_pInput->InitialUpdateFrame(NULL,true);
}

另外一种写法
CChildFrame* pFrame = new CChildFrame();
CCreateContext context;
context.m_pCurrentDoc=mp_doc; //that's the way I avoid to create new document every time I open

a new view
context.m_pNewViewClass=RUNTIME_CLASS(CTSMLView);
context.m_pNewDocTemplate=pDocTemplate;
context.m_pLastView=(((CMainFrame *)m_pMainWnd)->GetActiveFrame() ? ((CMainFrame

*)m_pMainWnd)->GetActiveFrame()->GetActiveView() : NULL);
context.m_pCurrentFrame=((CMainFrame *)m_pMainWnd)->GetActiveFrame();
if (!pFrame->LoadFrame(IDR_TSMLTYPE,WS_OVERLAPPEDWINDOW | FWS_PREFIXTITLE ,m_pMainWnd, &context

))return;
pFrame->InitialUpdateFrame(mp_doc,TRUE);


15、只能运行一个实例

//此程序只能运行一次,用互斥量来判断程序是否已运行
    HANDLE m_hMutex=CreateMutex(NULL,TRUE, m_pszAppName);
    if(GetLastError()==ERROR_ALREADY_EXISTS)
{
AfxMessageBox("程序已经运行!");
return FALSE;
}

16、在多文档界面下,自动生成一个新的子窗口,而一个实际的应用系统往往
是由用户操作后再生成新的窗口。为了去掉开始的子窗口,可在应用程序文件
分析命令行的语句

  CCommandLineInfo cmdInfo;

  ParseCommandLine(cmdInfo);

  后加入:

  cmdInfo.m_nShellCommand=CCommandLineInfo::FileNothing

17、if(AfxMessageBox("真的要退出吗?",MB_YESNO)==IDYES)
{
CDialog::OnOK();
}

18、ACCESS和SQL2000日期

access表示为:#1981-28-12# date BETWEEN #2005-04-28 23:59:59# AND #2005-05-24

23:59:59#
SQLSERVER2000表示为:'1981-02-12'       date BETWEEN '2005-03-21' AND '2005-05-24'

19、初始化应用程序的大小

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
      int xsize=::GetSystemMetrics(SM_CXSCREEN);
      int ysize=::GetSystemMetrics(SM_CYSCREEN);
      cs.cx=xsize*5/10;
      cs.cy=ysize*5/10;
      cs.x=(xsize-cs.cx)/2;
      cs.y=(ysize-cs.cy)/2;  
} 其中的5/10是你的初始界面占屏幕的百分比,可以自己修改。如果想使应用程序大小固定添加

cs.style&=~WS_THICKFRAME;

20、全屏FRAME
void CTestView::ShowFullScreen()
{
CMainFrame *pFrame=(CMainFrame *)(AfxGetApp()->m_pMainWnd);
if(m_bFullScreen)
{
pFrame->ModifyStyle(0,WS_CAPTION);
pFrame->ModifyStyle(0,WS_THICKFRAME);

pFrame->ShowWindow(SW_SHOWNORMAL);
m_bFullScreen=0;
}
else
{
pFrame->ModifyStyle(WS_CAPTION,0);
pFrame->ModifyStyle(WS_THICKFRAME,0);

pFrame->ShowWindow(SW_MAXIMIZE);
m_bFullScreen=1;
}
}

21、如何在对话框中从磁盘读出一个bitmap文件画在上面?

BOOL CAboutDlg::OnInitDialog()
{
   CDialog::OnInitDialog();
   HBITMAP m_hBmp = (HBITMAP)::LoadImage(0,
      "D:bitmap.bmp",
      IMAGE_BITMAP,
      0,
      0,
      LR_LOADFROMFILE | LR_CREATEDIBSECTION | LR_DEFAULTSIZE);
   _ASSERT(m_hBmp!=NULL);
   m_pBmp = CBitmap::FromHandle(m_hBmp);
   return TRUE;
}

void CAboutDlg::OnPaint()
{
   CPaintDC dc(this);
   BITMAP bm;
   CDC dcMem;
   VERIFY(m_pBmp->GetObject(sizeof(bm),(LPVOID)&bm));
   dcMem.CreateCompatibleDC(&dc);
   CBitmap *pOldBMP=(CBitmap *)dcMem.SelectObject(m_pBmp);
   BitBlt(dc.m_hDC,0, 0, bm.bmWidth, bm.bmHeight, dcMem.m_hDC, 0, 0, SRCCOPY);
   dcMem.SelectObject(pOldBMP);
   // Do not call CDialog::OnPaint() for painting messages
}


22、全屏显示Dialog
if(m_bFullScreen)
{
SetWindowPlacement(&m_OldWndPlacement);
}
else
{
GetWindowPlacement(&m_OldWndPlacement); //取得原始窗口位置
int nFullWidth = GetSystemMetrics(SM_CXSCREEN);
int nFullHeight = GetSystemMetrics(SM_CYSCREEN);

RECT WindowRect, ClientRect;
GetWindowRect(&WindowRect);
GetDlgItem(IDC_VIEW)->GetWindowRect(&ClientRect);

RECT FullScreenRect;
FullScreenRect.left = WindowRect.left - ClientRect.left;
FullScreenRect.top = WindowRect.top - ClientRect.top;
FullScreenRect.right = WindowRect.right - ClientRect.right + nFullWidth -

FullScreenRect.left;
FullScreenRect.bottom = WindowRect.bottom - ClientRect.bottom + nFullHeight -

FullScreenRect.top;

WINDOWPLACEMENT wndpl;
wndpl.length = sizeof(WINDOWPLACEMENT);
wndpl.flags = 0;
wndpl.showCmd = SW_SHOWNORMAL;
wndpl.rcNormalPosition = FullScreenRect;
SetWindowPlacement(&wndpl);

GetDlgItem(IDC_VIEW)->SetWindowPos(NULL, 0, 0, nFullWidth, nFullHeight, SWP_NOMOVE);
}
m_bFullScreen = !m_bFullScreen;

23、数据库连接串
//连接SQL SERVER
m_pConnection->Open("Driver=SQL

Server;Database=test;Server=127.0.0.1;UID=sa;PWD=;","","",adModeUnknown);
//连接ACCESS2000
m_pConnection->Open("Provider=Microsoft.Jet.OLEDB.4.0;Data

Source=userinfo.mdb","","",adModeUnknown);

24、void CDVRDlg::OnWindowPosChanging(WINDOWPOS FAR* lpwndpos)
{
//在窗口改变之前调用的方法:窗口的最小尺寸。
//CDialog::OnWindowPosChanging(lpwndpos); //注销这句避免无法最大化窗口
if (lpwndpos->cx < 400) lpwndpos->cx = 400;
if (lpwndpos->cy < 300) lpwndpos->cy = 300;

}

this->InvalidateRect(CRect(30,y-30,150,y-20),TRUE);//重新绘制矩形,用于更新时间。

void CDVRDlg::OnLButtonUp(UINT nFlags, CPoint point)
{
//点击鼠标响应事件
CRect changeApp_rect(77,119,41,95);

//判断是否在这个changeApp_rect区域,如果在就执行调用其它应用程序操作。
if(changeApp_rect.PtInRect(point))
{
if(AfxMessageBox("确定切换到笔录系统吗?",MB_YESNO)==IDYES)
{
   WinExec("D://test//Debug//DlgSplashScr.exe",SW_SHOW);
   OnClose();
}
}
}

25/
VC中常用的20种方法

一、打开CD-ROM
mciSendString("Set cdAudio door open wait",NULL,0,NULL);
二、关闭CD_ROM
mciSendString("Set cdAudio door closed wait",NULL,0,NULL);
三、关闭计算机
OSVERSIONINFO OsVersionInfo; //包含操作系统版本信息的数据结构
OsVersionInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
GetVersionEx(&OsVersionInfo); //获取操作系统版本信息
if(OsVersionInfo.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
{
//Windows98,调用ExitWindowsEx()函数重新启动计算机

DWORD dwReserved;
ExitWindowsEx(EWX_REBOOT,dwReserved); //可以改变第一个参数,实现注销用户、
//关机、关闭电源等操作
// 退出前的一些处理程序
}
四、重启计算机
typedef int (CALLBACK *SHUTDOWNDLG)(int); //显示关机对话框函数的指针
HINSTANCE hInst = LoadLibrary("shell32.dll"); //装入shell32.dll
SHUTDOWNDLG ShutDownDialog; //指向shell32.dll库中显示关机对话框函数的指针
if(hInst != NULL)
{
//获得函数的地址并调用之
ShutDownDialog = (SHUTDOWNDLG)GetProcAddress(hInst,(LPSTR)60);

(*ShutDownDialog)(0);
}
五、枚举所有字体
LOGFONT lf;
lf.lfCharSet = DEFAULT_CHARSET; // Initialize the LOGFONT structure
strcpy(lf.lfFaceName,"");
CClientDC dc (this);
// Enumerate the font families
::EnumFontFamiliesEx((HDC) dc,&lf,                                                                      

               
(FONTENUMPROC) EnumFontFamProc,(LPARAM) this,0);
//枚举函数
int CALLBACK EnumFontFamProc(LPENUMLOGFONT lpelf,
LPNEWTEXTMETRIC lpntm,DWORD nFontType,long lparam)

{
// Create a pointer to the dialog window
CDay7Dlg* pWnd = (CDay7Dlg*) lparam;
// add the font name to the list box
pWnd ->m_ctlFontList.AddString(lpelf ->elfLogFont.lfFaceName);
// Return 1 to continue font enumeration
return 1;
}
其中m_ctlFontList是一个列表控件变量
六、一次只运行一个程序实例,如果已运行则退出
if( FindWindow(NULL,"程序标题")) exit(0);
七、得到当前鼠标所在位置
CPoint pt;
GetCursorPos(&pt); //得到位置
八、上下文菜单事件触发事件:OnContextMenu事件

九、显示和隐藏程序菜单
CWnd *pWnd=AfxGetMainWnd();
if(b_m) //隐藏菜单
{
pWnd->SetMenu(NULL);
pWnd->DrawMenuBar();
b_m=false;
}
else
{
CMenu menu;
menu.LoadMenu(IDR_MAINFRAME); 显示菜单 也可改变菜单项
pWnd->SetMenu(&menu);
pWnd->DrawMenuBar();
b_m=true;
menu.Detach();
}
十、获取可执行文件的图标
HICON hIcon=::ExtractIcon(AfxGetInstanceHandle(),_T("NotePad.exe"),0);
if (hIcon &&hIcon!=(HICON)-1)
{
pDC->DrawIcon(10,10,hIcon);

}
DestroyIcon(hIcon);
十一、窗口自动靠边程序演示
BOOL AdjustPos(CRect* lpRect)
{//自动靠边
int iSX=GetSystemMetrics(SM_CXFULLSCREEN);
int iSY=GetSystemMetrics(SM_CYFULLSCREEN);
RECT rWorkArea;
BOOL bResult = SystemParametersInfo(SPI_GETWORKAREA, sizeof(RECT), &rWorkAre
a, 0);
CRect rcWA;
if(!bResult)
{//如果调用不成功就利用GetSystemMetrics获取屏幕面积
rcWA=CRect(0,0,iSX,iSY);
}
else
rcWA=rWorkArea;
int iX=lpRect->left;
int iY=lpRect->top;

if(iX < rcWA.left + DETASTEP && iX!=rcWA.left)
{//调整左
//pWnd->SetWindowPos(NULL,rcWA.left,iY,0,0,SWP_NOSIZE);
lpRect->OffsetRect(rcWA.left-iX,0);
AdjustPos(lpRect);
return TRUE;
}
if(iY < rcWA.top + DETASTEP && iY!=rcWA.top)
{//调整上
//pWnd->SetWindowPos(NULL ,iX,rcWA.top,0,0,SWP_NOSIZE);
lpRect->OffsetRect(0,rcWA.top-iY);
AdjustPos(lpRect);
return TRUE;
}
if(iX + lpRect->Width() > rcWA.right - DETASTEP && iX !=rcWA.right-lpRect->W

idth())
{//调整右
//pWnd->SetWindowPos(NULL ,rcWA.right-rcW.Width(),iY,0,0,SWP_NOSIZE);
lpRect->OffsetRect(rcWA.right-lpRect->right,0);
AdjustPos(lpRect);
return TRUE;
}
if(iY + lpRect->Height() > rcWA.bottom - DETASTEP && iY !=rcWA.bottom-lpRect
->Height())
{//调整下
//pWnd->SetWindowPos(NULL ,iX,rcWA.bottom-rcW.Height(),0,0,SWP_NOSIZE);
lpRect->OffsetRect(0,rcWA.bottom-lpRect->bottom);
return TRUE;
}
return FALSE;
}
//然后在ONMOVEING事件中使用所下过程调用

CRect r=*pRect;
AdjustPos(&r);
*pRect=(RECT)r;
十二、给系统菜单添加一个菜单项
给系统菜单添加一个菜单项需要进行下述三个步骤:
首先,使用Resource Symbols对话(在View菜单中选择Resource Symbols...可以显
示该对话)定义菜单项ID,该ID应大于0x0F而小于0xF000;
其次,调用CWnd::GetSystemMenu获取系统菜单的指针并调用CWnd:: Appendmenu将菜单
项添加到菜单中。下例给系统菜单添加两个新的
int CMainFrame:: OnCreate (LPCREATESTRUCT lpCreateStruct)
{

//Make sure system menu item is in the right range.

ASSERT(IDM_MYSYSITEM<0xF000);
//Get pointer to system menu.
CMenu* pSysMenu=GetSystemMenu(FALSE);
ASSERT_VALID(pSysMenu);
//Add a separator and our menu item to system menu.
CString StrMenuItem(_T ("New menu item"));
pSysMenu->AppendMenu(MF_SEPARATOR);
pSysMenu->AppendMenu(MF_STRING, IDM_MYSYSITEM, StrMenuItem);

}
十三、运行其它程序
//1、运行EMAIL或网址
char szMailAddress[80];
strcpy(szMailAddress,"
mailto:netvc@21cn.com");
ShellExecute(NULL, "open", szMailAddress, NULL, NULL, SW_SHOWNORMAL);

//2、运行可执行程序
WinExec("notepad.exe",SW_SHOW); //运行计事本
十四、动态增加或删除菜单
1、 增加菜单
//添加
CMenu *mainmenu;
mainmenu=AfxGetMainWnd()->GetMenu(); //得到主菜单
(mainmenu->GetSubMenu (0))->AppendMenu (MF_SEPARATOR);//添加分隔符
(mainmenu->GetSubMenu (0))->AppendMenu(MF_STRING,ID_APP_ABOUT,_T("Always on
&Top")); //添加新的菜单项
DrawMenuBar(); //重画菜单
2、 删除菜单
//删除
CMenu *mainmenu;
mainmenu=AfxGetMainWnd()->GetMenu(); //得到主菜单

CString str ;
for(int i=(mainmenu->GetSubMenu (0))->GetMenuItemCount()-1;i>=0;i--) //取得菜
单的项数。
{
(mainmenu->GetSubMenu (0))->GetMenuString(i,str,MF_BYPOSITION);
//将指定菜单项的标签拷贝到指定的缓冲区。MF_BYPOSITION的解释见上。
if(str=="Always on &Top") //如果是刚才我们增加的菜单项,则删除。
{
(mainmenu->GetSubMenu (0))->DeleteMenu(i,MF_BYPOSITION);
break;
}
十五、改变应用程序的图标
静态更改: 修改图标资源IDR_MAINFRAME。它有两个图标,一个是16*16的,另一个是3

2*32的,注意要一起修改。
动态更改: 向主窗口发送WM_SETICON消息.代码如下:
HICON hIcon=AfxGetApp()->LoadIcon(IDI_ICON);
ASSERT(hIcon);
AfxGetMainWnd()->SendMessage(WM_SETICON,TRUE,(LPARAM)hIcon);
十六、另一种改变窗口标题的方法
使用语句 CWnd* m_pCWnd = AfxGetMainWnd( ),然后,再以如下形式调用SetWindowTe
xt()函数:
SetWindowText( *m_pCWnd,(LPCTSTR)m_WindowText);// m_WindowText可以是一个CSt
ring类的变量。
十七、剪切板上通过增强元文件拷贝图像数据
下面代码拷贝通过元文件拷贝图像数据到任何应用程序,其可以放置在CView派生类的函

数中。
CMetaFileDC * m_pMetaDC = new CMetaFileDC();
m_pMetaDC->CreateEnhanced(GetDC(),NULL,NULL,"whatever");
//draw meta file
//do what ever you want to do: bitmaps, lines, text...
//close meta file dc and prepare for clipboard;
HENHMETAFILE hMF = m_pMetaDC->CloseEnhanced();
//copy to clipboard
OpenClipboard();
EmptyClipboard();
::SetClipboardData(CF_ENHMETAFILE,hMF);                                                                 

              
CloseClipboard();

//DeleteMetaFile(hMF);
delete m_pMetaDC;
十八、剪切板上文本数据的传送
把文本放置到剪接板上:
CString source;
//put your text in source
if(OpenClipboard())
{
HGLOBAL clipbuffer;
char * buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, LPCSTR(source));
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
从剪接板上获取文本:

char * buffer;
if(OpenClipboard())
{
buffer = (char*)GetClipboardData(CF_TEXT);
//do something with buffer here
//before it goes out of scope
}
CloseClipboard();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值