VC经典技巧代码(一)

 toolbar默认位图左上角那个点的颜色是透明色,不喜欢的话可以自己改。
 VC++中 WM_QUERYENDSESSION WM_ENDSESSION 为系统关机消息。
 Java学习书推荐:《java编程思想》
 在VC下执行DOS命令
   a.   system("md c:\\12");
   b.   WinExec("Cmd.exe /C md c:\\12", SW_HIDE);
   c.   ShellExecute
 ShellExecute(NULL,"open","d:\\WINDOWS\\system32\\cmd.exe","/c md d:\\zzz","",SW_SHOW);
   d.   CreateProcess
 下面这个示例的函数可以把给定的DOS命令执行一遍,并把DOS下的输出内容记录在buffer中。同时示范了匿名管道重定向输出的用法:

-------------------------------------------------------------------------------------
BOOL CDOSDlg::ExecDosCmd()
{    
 #define EXECDOSCMD "dir c:" //可以换成你的命令

 SECURITY_ATTRIBUTES sa;
 HANDLE hRead,hWrite;

 sa.nLength = sizeof(SECURITY_ATTRIBUTES);
 sa.lpSecurityDescriptor = NULL;
 sa.bInheritHandle = TRUE;
 if (!CreatePipe(&hRead,&hWrite,&sa,0)) 
 {
  return FALSE;
 } 
 char command[1024];    //长达1K的命令行,够用了吧
 strcpy(command,"Cmd.exe /C ");
 strcat(command,EXECDOSCMD);
 STARTUPINFO si;
 PROCESS_INFORMATION pi; 
 si.cb = sizeof(STARTUPINFO);
 GetStartupInfo(&si); 
 si.hStdError = hWrite;            //把创建进程的标准错误输出重定向到管道输入
 si.hStdOutput = hWrite;           //把创建进程的标准输出重定向到管道输入
 si.wShowWindow = SW_HIDE;
 si.dwFlags = STARTF_USESHOWWINDOW | STARTF_USESTDHANDLES;
 //关键步骤,CreateProcess函数参数意义请查阅MSDN
 if (!CreateProcess(NULL, command,NULL,NULL,TRUE,NULL,NULL,NULL,&si,&pi)) 
 {
  CloseHandle(hWrite);
  CloseHandle(hRead);
  return FALSE;
 }
 CloseHandle(hWrite);

 char buffer[4096] = {0};          //用4K的空间来存储输出的内容,只要不是显示文件内容,一般情况下是够用了。
 DWORD bytesRead; 
 while (true) 
 {
  if (ReadFile(hRead,buffer,4095,&bytesRead,NULL) == NULL)
   break;
  //buffer中就是执行的结果,可以保存到文本,也可以直接输出
  AfxMessageBox(buffer);   //这里是弹出对话框显示
 }
 CloseHandle(hRead); 
 return TRUE;
        }
 -------------------------------------------------------------------------------------

5 删除目录,包含删除子文件夹以及其中的内容

-------------------------------------------------
 BOOL DeleteDirectory(char *DirName)//如删除 DeleteDirectory("c:\\aaa")
 {
  CFileFind tempFind;
         char tempFileFind[MAX_PATH];
         sprintf(tempFileFind,"%s\\*.*",DirName);
         BOOL IsFinded=(BOOL)tempFind.FindFile(tempFileFind);
         while(IsFinded)
         {
                 IsFinded=(BOOL)tempFind.FindNextFile();
                 if(!tempFind.IsDots())
                 {
                         char foundFileName[MAX_PATH];
                        strcpy(foundFileName,tempFind.GetFileName().GetBuffer(MAX_PATH));
                         if(tempFind.IsDirectory())
                         {
                                 char tempDir[MAX_PATH];
                                sprintf(tempDir,"%s\\%s",DirName,foundFileName);
                                 DeleteDirectory(tempDir);
                         }
                         else
                         {
                                 char tempFileName[MAX_PATH];
                                sprintf(tempFileName,"%s\\%s",DirName,foundFileName);
                                 DeleteFile(tempFileName);
                         }
                 }
         }
         tempFind.Close();
         if(!RemoveDirectory(DirName))
         {
                 MessageBox(0,"删除目录失败!","警告信息",MB_OK);//比如没有找到文件夹,删除失败,可把此句删除
                 return FALSE;
         }
         return TRUE;
 }
 -------------------------------------------------------------
 让程序暂停:system("PAUSE");
 在PreTranslateMessage中捕捉键盘事件

     if (pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN)return TRUE; //注意return的值
 更改按键消息(下面的代码可把回车键消息改为TAB键消息)

-------------------------------------------------------
    BOOL CT3Dlg::PreTranslateMessage(MSG* pMsg) 
    {

        if(pMsg->message == WM_KEYDOWN && VK_RETURN == pMsg->wParam)    
       {
            pMsg->wParam = VK_TAB;
        }
        return CDialog::PreTranslateMessage(pMsg);
    }
 ------------------------------------------

 MoveWindow:  一个可以移动、改变窗口位置和大小的函数
10 16进制转化成10进制小数的问题
         用一个读二进制文件的软件读文件
         二进制文件中的一段 8F C2 F5 3C 最后变成了 0.03
         请问这是怎么转换过来的??
        方法一:浮点技术法,如
    DWORD dw=0x3CF5C28F; 
    float d=*(float*)&dw;//0.03;
     方法二:浮点的储存方式和整数完全两样,你想了解的话可以去
        http://www.zahui.com/html/1/3630.htm
        看一看,不过通常我们都不必了解它就可以完成转换。
        char a[4] = {0x8F, 0xC2, 0xF5, 0x3C};
        float f;
        memcpy(&f,a,sizeof(float));
                TRACE("%d",0x3CF5C28F);
11  EDIT控件的 EM_SETSEL,EM_REPLACESEL消息
12  在其它进程中监视键盘消息:用SetWindowsHookEx(WH_KEYBOARD_LL,...);
13  在桌面上任意位置写字

 --------------------------------------------------
 HDC deskdc = ::GetDC(0);
 CString stext = "我的桌面";
 ::TextOut(deskdc,100,200,stext,stext.GetLength());
 ::ReleaseDC(0,deskdc);
 ------------------------------------------------------
14   HWND thread_hwnd=Findwindow(NULL,"你要监控的进程窗体(用SPY++看)"),
         if (thread_hwnd==NULL) 。。。。。。。。。。
         else DWORD thread_id=GetWindowThreadProcessId (thread_hwnd,NULL)
15   waveOutGetVolume()可以得到波形音量大小
16   隐藏桌面图标并禁用右键功能菜单:
 ------------------------------------
 HWND Hwd = ::FindWindow("Progman", NULL);
  if (bShowed)
   ::ShowWindow(Hwd, SW_HIDE);
  else
   ::ShowWindow(Hwd, SW_SHOW);
  bShowed = !bShowed;
 ---------------------------------------
17   获得程序当前路径:
 ---------------------------------------------
 char ch[256];
 GetModuleFileName(NULL,ch,255);
 for(int i=strlen(ch);i && ch[i]!='\\';i--);
 ch[i]=0;
 AfxMessageBox(ch);
 ----------------------------------------------
18   KeyboardProc的lParam中包含着许多按键信息,其中第31位(从0开始)为0表示是按下按键,为1表示松开按键。
       (lParam & 0x80000000)进行二进制'与'计算,效果是取第31位的值。
       (lParam & 0x40000000)是取第30位,30位表示按键的上一个状态,为1表示之前键已经是按下的,0表示松开。
  lParam
  [in] Specifies the repeat count, scan code, extended-key flag, context code, previous key-state flag, and transition-state flag. For more information about the lParam parameter, see Keystroke Message Flags. This parameter can be one or more of the following values. 
  0-15
  Specifies the repeat count. The value is the number of times the keystroke is repeated as a result of the user's holding down the key.
  16-23
  Specifies the scan code. The value depends on the OEM.
  24
  Specifies whether the key is an extended key, such as a function key or a key on the numeric keypad. The value is 1 if the key is an extended key; otherwise, it is 0.
  25-28
  Reserved.
  29
  Specifies the context code. The value is 1 if the ALT key is down; otherwise, it is 0.
  30
  Specifies the previous key state. The value is 1 if the key is down before the message is sent; it is 0 if the key is up.
  31
  Specifies the transition state. The value is 0 if the key is being pressed and 1 if it is being released.
19   复制文件应该用到CopyFile或是CopyFileEx这两个API
20   移动窗口的位置或改变大小:MoveWindow/SetWindowPos
21   我的程序是当前运行的程序时,可以用setcursor()来设置光标的图标。
           而且可以用setcapture()是鼠标移动到我得程序窗口之外时也是我设置的图标
           但是如果我得程序不是当前的运行程序的,鼠标就会变会默认的。
           怎样能够,使得不变回默认的,还是用我设置的光标?
           SetSystemCursor
22   SendMessage函数的几个用法:
       控制按钮按下的,是这么用的
       SendMessage(n1, WM_COMMAND, MAKELPARAM(ID,BN_CLICKED),(LPARAM )n2); (n1,n2是句柄)
       而得到文本内容,是这样用的,
       SendMessage(hWnd,WM_GETTEXT,10,(LPARAM)buf),
23   处理一个单行EDIT的WM_CTLCOLOR要同时响应nCtlColor = CTLCOLOR_EDIT和CTLCOLOR_MSGBOX的两个情况,参考 http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_mfc_cwnd.3a3a.onctlcolor.asp
24   设备发生改变处理函数可在CWnd::OnDeviceChange中,捕获WMDEVICECHANGE事件不能区分诸如设备插入、拔下消息。
25   把字符"abc\n123"存入文本文件中时,文件内容没看见换行,其实用word打开该文件是有换行的。另外用"abc\r\n123"代替也可看见换行。
26 ::SetFocus(::GetDesktopWindow());或::BringWindowToTop(::GetDesktopWindow());
  ::GetDesktopWindow()这里可获得桌面窗口的句柄
27   数组初始化:
               int a[24][34];                           //声明数组
  memset(a,-1,24*34);                 //全部元素初始化成-1,但初始化成除0和-1以外的数值是不行的
28   SHGetFileInfo函数可获得文件信息。
29   创建一个控件:
             HWND hEdit=CreateWindow("EDIT",NULL,WS_CHILD|WS_VISIBLE |ES_LEFT,50,20,50,20,hwnd,NULL,hInst,NULL);     //hwnd参数为父窗口句柄
30   VC中对声音文件的操作: http://www.pujiwang.com/twice/Article_Print.asp?ArticleID=550
31   调用其它程序又要隐藏窗口:用CreateProcess函数调用,再拿到窗口句柄,然后::ShowWindow(hWnd,SW_HIDE);
32 读取文本文件中的一行:
   用CFile类的派生类:CStdioFile的方法:CStdioFile::ReadString
33   删除非空文件夹:
 ------------------------------------------------
 SHFILEOPSTRUCT  shfileop;  
 shfileop.hwnd  =  NULL;  
 shfileop.wFunc  =  FO_DELETE  ;  
 shfileop.fFlags  =  FOF_SILENT|FOF_NOCONFIRMATION;  
 shfileop.pFrom  =  "c:\\temp";        //要删除的文件夹
 shfileop.pTo  =  "";  
 shfileop.lpszProgressTitle  =  "";  
 shfileop.fAnyOperationsAborted  =  TRUE;  
 int  nOK  =  SHFileOperation(&shfileop); 
 -------------------------------------------------
34   函数前面加上::是什么意思?
   叫域运算符...在MFC中表示调用API...或其它全局函数...为了区分是mfc函数还是api
   详见: http://search.csdn.net/Expert/topic/1183/1183492.xml?temp=.9471247
35   CImageList的用法: http://www.study888.com/computer/pro/vc/desktop/200506/39027.html
36   有关控件的一些常见问答:
                    http://fxstudio.nease.net/article/ocx/                      <==========================很不错的地方哦
37   在多文档客户区中增加位图底图演示程序: 
                    http://www.study888.com/computer/pro/vc/desktop/200506/39028.html
       我的对应工程:AddBackgroundBitmap
38   用VC++6.0实现PC机与单片机之间串行通信
            http://www.zahui.com/html/1/1710.htm
39   日期到字符串:
 --------------------------------------------------
 SYSTEMTIME sys;
 GetSystemTime(&sys);
 char str[100];
 sprintf(str,"%d%d%d_%d%d%d",sys.wYear,sys.wMonth,sys.wDay,sys.wHour+8,sys.wMinute,sys.wSecond);
 //这里的小时数注意它的0:00点是早上8:00,所以要加上8,因为这是格林威治时间,换成我国时区要加8
 --------------------------------------------------
 CString m_strTemp;
 SYSTEMTIME systemtime;
 GetLocalTime(&systemtime);     //这个函数可获得毫秒级的当前时间
 m_strTemp.Format("%d年%d月%d日%d:%d:%d:%d   星期%d",systemtime.wYear,systemtime.wMonth,systemtime.wDay,systemtime.wHour,systemtime.wMinute,systemtime.wSecond,systemtime.wMilliseconds,systemtime.wDayOfWeek);
 --------------------------------------------------
40   任务栏上的图标闪烁:
   The FlashWindow function flashes the specified window once, whereas the FlashWindowEx function flashes a specified number of times.

 BOOL FlashWindow(
  HWND hWnd,     // handle to window to flash
  BOOL bInvert   // flash status
     );//闪烁一次
 FlashWindowEx()//闪烁多次
41  十六进制字符转浮点数:http://community.csdn.net/Expert/topic/4379/4379713.xml?temp=.7092096
   long lValue = 0xB28A43;
      float fValue;
      memcpy(&fValue,&lValue,sizeof(float));
42  在一个由汉字组成的字符串里,由于一个汉字由两个字节组成,怎样判断其中一个字节是汉字的第一个字节,还是第二个字节,使用IsDBCSLeadByte函数能够判断一个字符是否是双字的第一个字节,试试看:)  
 _ismbslead  
 _ismbstrail
43  如何实现对话框面板上的控件随着对话框大小变化自动调整
   在OnSize中依其比例用MoveWindow同等缩放.http://www.codeproject.com/dialog/dlgresizearticle.asp
44 向CListCtrl中插入数据后,它总是先纵向再横向显示,我希望他先横向再纵向
      在CListCtrl的ReDraw()中处理(见http://community.csdn.net/Expert/topic/4383/4383963.xml?temp=.3442041)
     如:
      m_list.ReDraw(FALSE);
      m_list.ReDraw(TRUE);
45  给你的程序加上splash:http://www.vckbase.com/document/finddoc.asp?keyword=splash
    如何添加闪屏:Project->Add to Project->Components and Controls->Gallery\\Visual C++ Components->Splash screen
46 实现象快速启动栏的"显示/隐藏桌面"一样的功能:http://fxstudio.nease.net/article/form/55.txt
47 如何设置listview某行的颜色:
   CSDN上的贴子:http://community.csdn.net/Expert/topic/4386/4386904.xml?temp=2.422512E-03
   Codeguru上相关链接:http://www.codeguru.com/Cpp/controls/listview/backgroundcolorandimage/article.php/c1093/
48 如何得到窗口标题栏尺寸:http://community.csdn.net/Expert/topic/4387/4387830.xml?temp=.6934168
 GetSystemMetrics(SM_CYCAPTION或者SM_CYSMCAPTION);

 SM_CYCAPTION Height of a caption area, in pixels. 
 SM_CYSMCAPTION Height of a small caption, in pixels.
 --------------------------------------------------------
 GetWindowRect(&rect);
 rect.bottom = rect.top + GetSystemMetrics(SM_CYSIZE) + 3;
 --------------------------------------------------------
49 如何将16进制的byte转成CString:

 ---------------------------------
 BYTE p[3];
 p[0]=0x01;
 p[1]=0x02;
 p[2]=0x12;
 CString str;
 str.Format("xxx", p[0], p[1], p[2]);
 -------------------------------------
50 怎样查找到正处在鼠标下面的窗口(具体到子窗口和菜单),无论是这个窗口是否具有焦点:
 -----------------------------------------------------------
 POINT pt;
 CWnd* hWnd;       // Find out which window owns the cursor
 GetCursorPos(&pt);
 hWnd=CWnd::WindowFromPoint(pt);
 if(hWnd==this)
 {
  //鼠标在窗体中空白处,即不在任何控件或子窗口当中
 }

51 得到CListCtrl控件点击事件时点击的位置:

 -----------------------------------------------
 void CTest6Dlg::OnClickList1(NMHDR* pNMHDR, LRESULT* pResult) 
 {NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR;
  if(pNMListView->iItem != -1)
  {
   CString strtemp;
   strtemp.Format("单击的是第%d行第%d列", 
   pNMListView->iItem, pNMListView->iSubItem);
   AfxMessageBox(strtemp);
  }
  *pResult = 0;
 }
 ------------------------------------------------
52   如何在clistctrl的单元格里添加图片? http://community.csdn.net/Expert/topic/4388/4388748.xml?temp=.2233393

53  自己处理按键响应函数:

 -------------------------------------------------
 BOOL CTest6Dlg::PreTranslateMessage(MSG* pMsg) 
 {
  if( pMsg->message == WM_KEYDOWN )
  {   
  if(pMsg->hwnd == GetDlgItem(IDC_EDIT1)->m_hWnd)     //判断当前控件是不是编辑框
  {
  switch( pMsg->wParam )
  {
  case VK_RETURN:             //如果是回车键的话
  Onbutton1();                //就调用Button1的响应函数
  }
  }
 return CDialog::PreTranslateMessage(pMsg);
 }
 ---------------------------------------------------
54   如何在VC中操纵word: http://www.vckbase.com/document/viewdoc/?id=1174
55   两个像素(用RGB表示)如何确定亮度等级: 
         加权算出灰度值:R*0.21+Green*0.70+Blue*0.09,或:
         ((红色值 X 299) + (绿色值 X 587) + (蓝色值 X 114)) / 1000
56   对已画在CDC上的图片进行处理,实现任意比例的透明度。
  MSDN: http://msdn.microsoft.com/msdnmag/issues/05/12/CatWork/
实现方法是:
1、用GetCurrentBitmap得到DC上的CBitmap指针;
2、用GetBitmapBits得到CBitmap上的图像数据流;
3、对图像数据流中每个字节进行转换,转换的公式为
       pBits[i] += (255 - pBits[i]) * nTransparent / 100;//nTransparent为透明度的百分率

57  MFC很多API函数的源代码都在:VC安装目录\VC98\MFC\SCR\WINCORE.cpp文件中。
58  自己写了个函数,用来获得ANSI字符串中真实字符的个数,如“I服了U”的长度返回4:

 --------------------------------------------------
 int GetCount(CString str)
 {
  int total=0;
  for(int i=0;i<str.GetLength();i++)
  {
   if (127<(unsigned int)str.GetAt(i))
   {
    total++;
    i++;
   }
   else
    total++;
  }
  return total;
 }
 ----------------------------------------------------
59   消息传递中pMSG中一些参数的意义:
  hwnd-------接收消息的窗口句柄;
  message----发送的消息号;
  wParam-----消息参数,具体意义同发送的消息有关;
  lParam-----同上;
  time-------发送消息时的时间,数值大小为自系统启动以来经历的时间,单位是毫秒;
  pt---------发送消息时鼠标在屏幕上的绝对坐标,单位是像素。
60   刷新屏幕局部:
刷新控件区域:
控件ID:IDC_STATIC_STATIC
 ------------------------------------
 CRect static_rect;
 CWnd *pwnd = GetDlgItem(IDC_STATIC_STATIC);
 if (pwnd == NULL)
 {
  return;
 }
 pwnd->GetWindowRect(&static_rect);
 ScreenToClient(&static_rect);
 InvalidateRect(&static_rect);    //注意这个函数,会调用OnEraseBkgnd
 --------------------------------------
61   VC实现录音,放音,保存,打开功能:  http://www.pconline.com.cn/pcedu/empolder/gj/vc/0412/509819.html
62   获得任务栏高度:
 ----------------------------------
 HWND hWnd = FindWindow("Shell_TrayWnd", NULL);
 RECT rc;
 ::GetWindowRect(hWnd, &rc);
 int iHeight = rc.bottom -rc.top;
 -----------------------------------
63   vc控制word、excel的问题: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnoxpta/html/vsofficedev.asp
       下面还有范例两个:
          http://www.vckbase.com/code/downcode.asp?id=2415
          http://www.vckbase.com/code/downcode.asp?id=2397

64 给ListBox控件加上水平滚动条:m_list.SetHorizontalExtent(100); //m_list为和listbox控件绑定的CListBox变量
65  下拉式的工具条按钮:http://community.csdn.net/Expert/topic/4413/4413094.xml?temp=.2334864
66 如何让MFC基于Dialog的程序在任务栏中显示:http://community.csdn.net/Expert/topic/4413/4413492.xml?temp=.3407404
67 制作一个没有标题栏.菜单栏和工具栏的视窗,就象游戏界面一样:
   http://community.csdn.net/Expert/topic/4396/4396239.xml?temp=.568783
68 为何组合框Droplist风格时响应键盘PreTranslateMessage函数,而dropdown风格时不响应:
   http://community.csdn.net/Expert/topic/4412/4412791.xml?temp=.8741419
69 直接用特殊字符的编码:s=WCHAR(0x00e6);     //还没试过
70 在标题栏上画图:http://community.csdn.net/Expert/topic/4416/4416434.xml?temp=.8910944
71 如何精确延时:http://www.vckbase.com/document/viewdoc/?id=1301
72 怎样给TreeView控件中的结点重命名:http://community.csdn.net/Expert/topic/4409/4409069.xml?temp=.1730463
73 从内存中加载并启动一个exe :http://community.csdn.net/Expert/topic/4418/4418306.xml?temp=.7619135
74 修改一个EXE的资源:http://community.csdn.net/Expert/topic/4420/4420755.xml?temp=.5104029
75 使用并显示64bit数值的方法:

 __int64 ld = 2000000000*4500000000;   //64bit数的范围:-9223372036854775808~+9223372036854775807
 printf("%I64d\n",ld);
76 在程序中使用console窗口显示: http://www.codeguru.com/Cpp/W-D/console/
  在里面找一下:Redirection
77 用代码画鼠标图案并限定鼠标移动区域(用ClipCursor函数):
     http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winui/winui/windowsuserinterface/resources/cursors/usingcursors.asp
78 改变编辑框字体的大小: http://community.csdn.net/Expert/topic/4389/4389148.xml?temp=.2317163
  先在对话框类的内部声明一个CFont对象,如:CFont myfont;
 ---------------------------------
 myfont.CreatePointFont(500, "Arial");
 GetDlgItem(IDC_EDIT1)->SetFont(&myfont);
 ---------------------------------
79 bmp图片怎么转换为jpg:
  用cximage
   www.codeproject.com上有
80 字符串转成UTF-8格式参考CSDN上的FAQ: http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=191432
81 将16进制字符串转换成10进制整数:
   char a[3]="ab";
   DWORD val = strtoul(a, NULL, 16);
82 快速从数字的字符串中提取出特定长度的数字:
 -------------------------------------------------------
 int a[4];
 sscanf("2004115819185","dddd",&a[0],&a[1],&a[2],&a[3]);   //按指定长度分隔
 --------------------------------------------------------
  或:
 -------------------------------------------------------
 CString s="aaa,bbb,ccc,ddd";
 char a1[4],a2[4],a3[4],a4[4];                       //这里要注意多留点空间以存放各子串的长度
 sscanf(s,"%[^,],%[^,],%[^,],%[^,]",a1,a2,a3,a4);    //按指定字符(这里是逗号)分隔
 AfxMessageBox(a4);//显示ddd
 -------------------------------------------------------
83 配置文件的配置项可不可以删除: http://community.csdn.net/Expert/topic/4402/4402346.xml?temp=.4008448
84 如何改变CListCtrl包括Scrollbars和Column Headers的颜色和风格: http://www.codeguru.com/Cpp/controls/listview/backgroundcolorandimage/print.php/c4185/
85 根据ComboBox加入的字符串的长度自动调整ComboBox控件的宽度:
  //这里假设为ComboBox加入两个字符串
  CString str1="中华人民共和国中华人民共和国",str2="1234567890123中国89012345678";
  m_combo.AddString(str1);    //m_combo为绑定在组合框控件的变量
  m_combo.AddString(str2);
  int len=str1.GetLength()*6.2;   //根据加入的字符串长度(以字节为单位)和组合框使用的默认字体的大小计算组合框实际需要的宽度,计算中间用到了整数->浮点数->整数的两次数值类型隐式转换,也可以用winAPI函数GetTextExtentPoint32()或GetTextExtent计算
  m_combo.SetDroppedWidth(len);
86 弹出U盘: http://community.csdn.net/Expert/topic/4432/4432968.xml?temp=.8724634
87 往另一个程序的编辑框中发送文字:句柄->SendMessage(WM_SETTEXT,strlen(buf),(LPARAM)buf);      //buf为你要加入的char*
88 如何在RichEdit中加超链接: http://community.csdn.net/Expert/topic/4434/4434686.xml?temp=9.524173E-02
89 VC控件的用法: http://www.vckbase.com/document/indexold.html
90 学习资源: http://code.ddvip.net/list/sort000081_1.html
91 在初始时候定位到LIST的指定行(如第100行)开始显示:EnsureVisible(100)           //未验证
92 如何在app中SetTimer(): http://community.csdn.net/Expert/topic/4437/4437002.xml?temp=6.014651E-02
              http://search.csdn.net/Expert/topic/1422/1422546.xml?temp=.5501825
93 一个基于SDK的软键盘的范例,可以学习如何发送虚拟按键或鼠标消息: http://www.codeproject.com/cpp/togglekeys.asp
94 MDI文档中的字体、及其颜色怎么设置: http://community.csdn.net/Expert/topic/4396/4396003.xml?temp=.7866938
95 自己捕捉特定的组合键: http://community.csdn.net/Expert/topic/4439/4439270.xml?temp=.7411157
                                                    http://community.csdn.net/Expert/topic/4484/4484120.xml?temp=.3993799
 --------------------------------------------------------------
 BOOL CMMDlg::PreTranslateMessage(MSG* pMsg) 
 {
  // TODO: Add your specialized code here and/or call the base class
  BOOL b = GetAsyncKeyState(VK_CONTROL) >> ((sizeof(short) * 8)-1);
  if(b)
   {    
   b = GetAsyncKeyState(VK_MENU) >> ((sizeof(short) * 8)-1);
   if(b)
    {    
     b = GetAsyncKeyState(65) >> ((sizeof(short) * 8)-1);  //这里不分大小写
     if(b)
      {
       AfxMessageBox("你按下了Ctrl+Alt+A组合键。") ;
      }
    }
   }
         
  return CDialog::PreTranslateMessage(pMsg);
 }
 -------------------------------------------------------------
  另外,GetAsyncKeyState和::GetKeyState这两个函数也可以帮你检测Shift、Ctrl和Alt这些键的状态。
96 快速从得到的全路径文件名中分离出盘符、路径名、文件名和后缀名:
 ------------------------------------------------
 char path_buffer[_MAX_PATH];   
 char drive[_MAX_DRIVE];   
 char dir[_MAX_DIR];
 char fname[_MAX_FNAME];   
 char ext[_MAX_EXT];
 GetModuleFileName(0,path_buffer,_MAX_PATH);
 _splitpath( path_buffer, drive, dir,fname , ext);     //用这个函数转换
 ------------------------------------------------
97 如何debug除零错误: http://community.csdn.net/Expert/topic/4440/4440273.xml?temp=.2427484
98 修改VS.net“工具”栏中菜单的默认图标: http://www.codeproject.com/dotnet/vsnet_addin_icon_change.asp
99 在窗口的标题栏和菜单栏上象realplayer那样添加自己的logo: http://www.codeproject.com/menu/menuicon.asp
100 个性化的位图菜单,自己从CMenu派生子类实现: http://www.codeguru.com/Cpp/controls/menu/bitmappedmenus/article.php/c165
                                                                                                http://www.codeguru.com/Cpp/controls/menu/bitmappedmenus/article.php/c163
101 怎样取得程序自己占用的内存和CPU占用率:GetProcessMemoryInfo和GetPerformanceInfo
102 如何让你的程序运行在release模式下:build->set active configuration
103 监视文件夹是否被更新:FindFirstChangeNotificat ion、FindNextChangeNotificati on、FindCloseChangeNotificat ion这三个函数
                         范例见: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/fileio/fs/obtaining_directory_change_notifications.asp
105 动态菜单: http://community.csdn.net/Expert/topic/4441/4441893.xml?temp=.2887384
    http://community.csdn.net/Expert/topic/4506/4506791.xml?temp=.2409326
106 如何获取客户区的中心坐标: http://community.csdn.net/Expert/topic/4449/4449444.xml?temp=8.642215E-02
107 强行操作内存虚拟地址中某个指定地方的内容:
 ----------------------------------------------
 int *a=(int*)0x00440000;     //这里以访问0x00440000地址为例
 cout<<*a<<endl;
 ----------------------------------------------
108 如何响应条码机: http://community.csdn.net/Expert/topic/4453/4453026.xml?temp=.1966516
     条码扫描仪主要有三种接口: 1.RS232 2.共用接盘接口 3.USB外设.   对于RS232,需要编程来监视和读取条码; 对于共用接盘接口,条码信息被转换成相应的键盘消息,具有输入焦点的应用程序会收到键盘输入消息,我们以前的做法是做一个全局keyboard Hook或应用程序级别上 keyboard hook, 监视键盘消息,当有连续的键盘消息(在很短的时间内),并且这些键盘字符能构成完成的条码信息,就产生一条自定义消息,通知窗口(向监视程序注册的窗口)条码信息到达,条码机只是相当于一个键盘,所以你也可以在界面上放一个edit框,条码机读出条码后还会在字符串后面加一个回车(这个一般是可设置的,可加可不加),如果条码机自动加回车,则你重写OnOK函数,将edit框的内容取出放入list即可。

当然也可不放edit框,而直接接收键盘字符(比如重写OnChar函数等,方法很多),但要考虑到这种情况:条码读不出来的情况,此时应该用手动输入条码,所以还是放一个edit框为好。

109 检查指定文件夹是否存在:PathIsDirectory()
 方法一:
  检查给定路径是否根目录:BOOL PathIsRoot(LPCTSTR pPath);
  说明:Returns TRUE for paths such as “\”, “ X:\”, “\\ server\ share”, or “\\ server\”。Paths such as “..\path2” will return FALSE.
     用这两个函数要先:#include <shlwapi.h>;
         再把这个文件加入工程:shlwapi.lib
 方法二:
  GetFileAttributes检查文件是否存在,并且检查是否文件夹属性FILE_ATTRIBUTE_DIRECTORY

 ----------------------------------------------------------
 DWORD = GetFileAttributes(_T("f:\\win98"));
 if(dwAttr != 0xFFFFFFFF && (dwAttr & FILE_ATTRIBUTE_DIRECTORY))
  cout<<"exist"<<endl;
 else
  cout<<"NOT exist"<<endl;
 ----------------------------------------------------------
  方法三:
    用下面第113条的_access函数同样可以
 ----------------------------------------------------------
 if(_access("f:\\win98",0)!=-1)
  cout<<"exist"<<endl;
 else
  cout<<"NOT exist"<<endl;
 ----------------------------------------------------------
  方法四:
    用PathFileExists函数,见MSDN介绍,需要的条件同方法一。
  还有一个:BOOL SHGetPathFromIDList(LPCITEMIDLIST pidl,LPTSTR pszPath);
    Converts an item identifier list to a file system path.
110 去掉单文档标题栏上的“无标题—”: http://community.csdn.net/Expert/topic/4454/4454093.xml?temp=.2896997
111 打开显示器: ::SendMessage(GetSafeHwnd(), WM_SYSCOMMAND, SC_MONITORPOWER, -1);   //从bobob的blog上抄来的^_^
   关闭显示器: ::SendMessage(GetSafeHwnd(), WM_SYSCOMMAND, SC_MONITORPOWER, 1);   //从bobob的blog上抄来的^_^
   得到它的工作状态:
休眠状态是指用SendMessage(Handle, WM_SYSCOMMAND, SC_MONITORPOWER, -1)关闭的
--------------------------------------------------------------------------------
The GetDevicePowerState function is supposed to retrieve the current power state of the specified device. However, Apps may fail to use GetDevicePowerState on the display, as they can't get a handle on " \\.\Display#", while the # index is 1-based, or " \\.\LCD", for security reasons. 
If you are trying to do this on Windows XP, then you can use SetupDiGetDeviceRegistry Property and Property: SPDRP_DEVICE_POWER_DATA to get the power management information. This is documented in the Windows XP DDK. 
The WMI Class Win32_DesktopMonitor does not report the power state. use SPI_GETPOWEROFFACTIVE or DeviceIOControl with IOCTL_VIDEO_GET_POWER_MANAGEMENT will simply reports power management is enabled or not. SPI_GETPOWEROFFACTIVE just determines whether the power-off phase of screen saving is enabled or not.
BTW, you can always use the SetThreadExecutionState or other APIs (you have used) to switch ON the monitor no matter the monitor is in the ON or OFF state. 
References
http://msdn.microsoft.com/library/en-us/Display_r/hh/Display_r/VideoMiniport_Functions_b47b2224-5e0b-44af-9d04-107ff1299381.xml.asp
http://msdn.microsoft.com/library/en-us/wmisdk/wmi/win32_desktopmonitor.asp
112 得到系统时间、语言等的设置
  GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_ITIME, lpLCData, cchData);   //从bobob的blog上抄来的^_^
113 文件是否存在(记得先包含头文件#include <io.h>)
 ----------------------------------
 if(_access("c:\\somefile.txt",0)!=-1)
  //存在
 else
  //不存在
 ---------------------------------
 还有一个方法:
 ---------------------------------------------
 if(GetFileAttributes("f:\\test.txt")!=0xFFFFFFFF)
 {
  //存在
 }
 else
 {
  //不存在
 }
 ---------------------------------------------
114 得到剪贴板数据
 -------------------------------------------------
 if ( OpenClipboard() )                       
 {
  HANDLE hData = GetClipboardData(CF_TEXT);
  char * buffer = (char*)GlobalLock(hData);     //剪贴板中的文本内容保存在buffer中
  GlobalUnlock(hData);
  CloseClipboard();
 }
 ----------------------------------------------
115 在CStatic上面关联图片
 ----------------------------------------------
 CStatic* pWnd = (CStatic*)GetDlgItem(IDC_STATIC);
 pWnd->ModifyStyle(0, SS_BITMAP);
 pWnd->SetBitmap((HBITMAP)::LoadImage(0,
  "c:\\zzzzz.bmp",                        //只能显示.bmp文件
  IMAGE_BITMAP,
  0,0,LR_CREATEDIBSECTION |LR_DEFAULTSIZE |LR_LOADFROMFILE));
 ----------------------------------------------
116 显示一个打开文件夹的对话框,并得到用户选择的目录:

 -------------------------------------------
 char szDir[MAX_PATH];
 BROWSEINFO bi;
 ITEMIDLIST *pidl;
 bi.hwndOwner = this->m_hWnd;
 bi.pidlRoot = NULL;
 bi.pszDisplayName = szDir;
 bi.lpszTitle = "请选择目录";//strDlgTitle;
 bi.ulFlags = BIF_RETURNONLYFSDIRS;
 bi.lpfn = NULL;
 bi.lParam = 0;
 bi.iImage = 0;

 pidl = SHBrowseForFolder(&bi);
 if(pidl == NULL) 
 return;
 if(!SHGetPathFromIDList(pidl, szDir)) 
 return;
 AfxMessageBox(szDir);    //szDir中存放的内容为用户选定的目录
 ------------------------------------------------

117 去除字符串中指定的字符:

 -----------------------------------------
 CString strtemp;
 strtemp.Format("%s","abc\n123\ndef");
 strtemp.Remove('\n');     //这里以去除换行符为例,结果保存在strtemp中了
 -------------------------------------------
118 有关数据结构的地址: http://student.zjzk.cn/course_ware/data_structure/web/main.htm
119 假如当前时间2005-09-09,如何计算在该时间前12345天,是哪年哪月哪日?
 ---------------------------
 CTime tm(2005,9,9,0,0,0);
 tm-=86400*12345;
 cout<<tm.Format("%Y-%m-%d")<<endl;
 ----------------------------
120 PeekMessage是干什么用的:  http://community.csdn.net/Expert/topic/4462/4462828.xml?temp=.8852045
121 拖动控件时实现类似windows拖动窗口的效果:CRectTracker
       Mackz朋友的blog中有它的范例: http://blog.csdn.net/Mackz/archive/2005/10/27/517747.aspx
122 有关UNICODE、ANSI字符集和相关字符串操作的总结: http://community.csdn.net/Expert/FAQ/FAQ_Index.asp?id=199372
123 寻找系统中的打印机:EnumPrinters                             
124 用代码加入外部模块的方法:#pragma comment(lib,"mylib.lib")
125 判断指定点是否在一个矩形框内:CRect::PtInRect(POINT point)
126 winAPI 函数GetTextExtentPoint32()可以得出一个以像素为单位的字符串的宽度。
127 RGB转换成YV12(YUV 4:2:0)的方法: http://www.fourcc.org/fccyvrgb.php
128 获得指定进程占用内存的情况,用GetProcessMemoryInfo()函数。
129 把CONSOLE程序的输出导入到文件中,用程序控制: http://community.csdn.net/Expert/topic/4403/4403431.xml?temp=.7469599
                                                                                                  http://www.codeproject.com/dialog/quickwin.asp
130 把CRichEditCtrl中的文字保存到rtf文件: http://community.csdn.net/Expert/topic/4478/4478640.xml?temp=.1313135         
   在codeproject上还有从CRichEditCtrl类派生新类的,功能增强了很多: http://www.codeproject.com/richedit/autoricheditctrl.asp
   还有一个开发类似写字板那样程序的完整范例: http://www.codeproject.com/tools/simplewordpad.asp
131 MFC中使用ATL字符转换宏:在你的函数开关加上USES_CONVERSION;语句,详见MSDN或这里: http://community.csdn.net/Expert/topic/4479/4479609.xml?temp=.6256983
132 如何建立共享目录:直接调用标准的Win32API函数NetShareAdd和NetShareDel
   详见MSDN及: http://community.csdn.net/Expert/topic/4481/4481371.xml?temp=.4405023
133 位图文件读写基础: http://www.vckbase.com/document/viewdoc/?id=674
134 用VC实现支持多语言的程序: http://www.vckbase.com/document/viewdoc/?id=1102                                   //还没试过,以后用到了再仔细研究吧
135 Menu系列函数:
         GetMenu
         GetMenuInfo
         GetMenuItemCount
         GetMenuItemID
         GetMenuString
         EnableMenuItem 
         CheckMenuItem
         ModifyMenu
         RemoveMenu
         InsertMenu
         GetSystemMenu
         ::LoadMenu
         ::SetMenu
136 得到SYSTEMMENU(系统菜单)的高度:GetSystemMetrics(SM_CYMENU);
   得到当前屏幕分辨率:
  GetSystemMetrics(SM_CXFULLSCREEN);           //得x值(如1024)
  GetSystemMetrics(SM_CYFULLSCREEN);           //得y值( 如768-任务栏高度)
         此外这个函数还可以得到很多别的系统设置值,详见MSDN: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/sysinfo/base/getsystemmetrics.asp
137 在属性页控件的标签上加图片: http://www.codeguru.com/cpp/controls/propertysheet/article.php/c611/
        http://community.csdn.net/Expert/topic/4492/4492593.xml?temp=.9977991
 --------------------------------------------------
 BOOL CMyPropSheet::OnInitDialog()
 {
 BOOL bResult = CPropertySheet::OnInitDialog();
 m_imageTab.Create( IDB_TABIMAGES, 13, 1, RGB(255,255,255) );
 CTabCtrl *pTab = GetTabControl();
 pTab->SetImageList( &m_imageTab );

 TC_ITEM tcItem;
 tcItem.mask = TCIF_IMAGE;
 for( int i = 0; i < 3; i++ )
 {
  tcItem.iImage = i;
  pTab->SetItem( i, &tcItem );
 }
 return bResult;
 }
 ----------------------------------------------------


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值