VC雕虫小技集(三)

VC雕虫小技集(三)
何志丹
1,固定窗口大小,最大值为(600,400),最小值也为(600,400).
void CMainFrame::OnGetMinMaxInfo(MINMAXINFO FAR* lpMMI)
{
lpMMI->ptMaxTrackSize.x = 600;
lpMMI->ptMaxTrackSize.y = 400;
lpMMI->ptMinTrackSize.x = 600;
lpMMI->ptMinTrackSize.y = 400;
CFrameWnd::OnGetMinMaxInfo(lpMMI);
}

2,关闭对话框和窗口:
其实,一般窗口的销毁可以用DestoryWindow(),对话框的销毁可以用EndDialiog().
EndDialog(IDOK);
DoModal()的返回值为IDOK,但不会执行用户定义的OnOK.
只要发送WM_CLOSE消息,就会有响应的函数处理的。
SendMessage(WM_CLOSE);
PostMessage(WM_CLOSE);
void CTestDialog::OnButton1()
{
GetParent()->DestroyWindow();
}
窗口和对话框一起关
PostMessage(WM_QUIT);
SendMessage(WM_QUIT);//不行
无模式对话框用DestroyWindow();
用EndDialog
你再打开原对话框就有问题

3,全局变量的使用:
C***App中定义一个CString
使用时
void CDlgDlg::OnButton2()
{
((CDlgApp*)AfxGetApp())->str = "test";
}
不要忘记了包含文件

4,如何让dos程序开机自动运行并且不显示自动运行好解决 ,写注册表run值,vc+windows2000
把main改为winmain

5,清除自动密码历史记录
浏览器中:工具->Internet选项->内容->点"自动完成(U)"按钮->清除密码http://tzsvc.xiloo.com/skill/sys/clear.htm
SHDeleteKey(HKEY_CURRENT_USER,_T("Software//Microsoft//Internet Explorer//IntelliForms"));

6,执行一个可执行程序
方法一:
ShellExecute(this->GetSafeHwnd(),"Open","f://he.txt",NULL,NULL,SW_SHOWNORMAL );
方法二:
PROCESS_INFORMATION pi;
STARTUPINFO si;
si.cb = sizeof(STARTUPINFO);
si.lpReserved = NULL;
si.lpDesktop = NULL;
si.lpTitle = NULL;
si.dwFlags = 0;
si.cbReserved2 = 0;
si.lpReserved2 = NULL;
BOOL bres = CreateProcess(NULL,"test a.txt b.txt",NULL,NULL,false,NORMAL_PRIORITY_CLASS,NULL,NULL,&si,π);
if(bres==false)
{
    AfxMessageBox("CreateProcess failed");
}
else
{
    CloseHandle(pi.hThread);
    DWORD dwret=WaitForSingleObject(pi.hProcess, 1000*30);
    switch(dwret)
    {
    case WAIT_OBJECT_0:
    DWORD dwexitcode;
    bres = GetExitCodeProcess(pi.hProcess,&dwexitcode);
    TCHAR exitmsgbuf[1024];
    if(bres)
    {
    wsprintf(exitmsgbuf,"exit code:%d",dwexitcode);
    }
    else
    wsprintf(exitmsgbuf,"exit code failed to return");
    AfxMessageBox(exitmsgbuf);
    break;
    default:
    AfxMessageBox("exit for other reason");
}

VC雕虫小技集(四)
何志丹

1, 阅读程序常常要看此变量在那些地方值改变过
ctrl+f查找太麻烦
将此变量前加const
改变的地方报错

2, 看一个函数被那些函数调用.
方法:
1,调试状态下,view->debug window->call Stack
2,class view 的快捷菜单中选择called by


3, 在状态栏的最左边显示时间
static UINT indicators[] =
{
ID_SEPARATOR,//我们增加的
ID_SEPARATOR,
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
..... m_wndStatusBar.SetPaneInfo(1,ID_SEPARTOR,SBPS_NORMAL,60);
}
//菜单的响应函数
void CMainFrame::OnTest()
{
CTime t;
t = CTime::GetCurrentTime();
CString str = t.Format("%H - %M -%S");
m_wndStatusBar.SetPaneText(0,str);
}

4,模拟鼠标
::SetCursorPos((int)ptMouse->x,(int)ptMouse->y);
::mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
::mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);
::mouse_event(MOUSEEVENTF_LEFTDOWN,0,0,0,0);
::mouse_event(MOUSEEVENTF_LEFTUP,0,0,0,0);

5,什么是WORD, DWORD
typedef unsigned short WORD
typedef unsigned long DWORD

6,移动控件
CWnd * pWnd = GetDlgItem(IDC_BUTTON1);
CRect r;
pWnd->GetWindowRect(&r);
r.left +=50;
r.right += 50;
pWnd->MoveWindow(r);

7, 如何让对话框中的CEdit响应ENTER键回车
GetDlgItem(IDC_EDIT1)->SetWindowText("111/r/n22");
右键属性
sytle -> Multiline选上
最好把want return 也选上

8,将c语言转化为汇编
VC++ provides this feature.
Project->Settings...
C/C++ tab
Category: Choose Listing Files
Listing file type:
select "Assembly with source code"

9,如何获得进程所消耗的CPU时间?
BOOL GetProcessTimes(HANDLE hProcess,LPFILETIME lpCreationTime,LPFILETIME lpExitTime,LPFILETIME lpKernelTime,LPFILETIME lpUserTime);

10,如何通过扩展名得到该扩展名所对应的图标?
SHGetFileInfo(path,attr,&sfi,sizeof(SHFILEINFO),SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_TYPENAME);
如何在拉着对话框的边框改变大小时,让它成比例的变化.就像视频播放软件哪样处理wm_sizing消息
void CTest 1Dlg::OnSizing(UINT fwSide, LPRECT pRect)
{
    CDialog::OnSizing(fwSide, pRect);
    if((fwSide==WMSZ_BOTTOM) || (fwSide==WMSZ_TOP))
    pRect->right=pRect->left+(pRect->bottom-pRect->top)*2;
    else
    pRect->bottom=pRect->top+(pRect->right-pRect->left)*0.5;
}

VC雕虫小技集(五)
何志丹

1,vc中右键点击一个类或宏,可以察看他的定义,但如何返回初始地方呢?
install visual assist, and use Alt+left arrow
按菜单中的 后退 (<- 转45度)按钮
好像是又打开了一个文档,关闭它就行了

2,怎样获取系统菜单,并且弹出系统菜单?
void CTestsysmenuDlg::OnOK()
{
// click the OK button to show system menu(masterz)
POINT curPos;
GetCursorPos(&curPos);
SetForegroundWindow();
CMenu* pMenu=GetSystemMenu(false);
int nSelection=pMenu->TrackPopupMenu(TPM_LEFTBUTTON | TPM_LEFTALIGN |TPM_BOTTOMALIGN|TPM_NONOTIFY|TPM_RETURNCMD, curPos.x, curPos.y, this);
DWORD dwpos= curPos.x + ((curPos.y<<16)&0xffff0000);
SendMessage(WM_SYSCOMMAND,nSelection,dwpos);
CString msg;
msg.Format("x:%d,y:%d; cursor.x=%d,cursor.y=%d",LOWORD(dwpos),HIWORD(dwpos),curPos.x,curPos.y);
OutputDebugString(msg);
}

3, 如何控制键盘上面的3 个灯的亮灭 (NUM LOCK ,CAPS LOCK SRCOLL LOCK)
#include
void SetNumLock( BOOL bState )
{
    BYTE keyState[256];
    GetKeyboardState((LPBYTE)&keyState);
    if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||(!bState && (keyState[VK_NUMLOCK] & 1)) )
    {
        // Simulate a key press
        keybd_event( VK_NUMLOCK,0x45,KEYEVENTF_EXTENDEDKEY | 0,0 );
        // Simulate a key release
        keybd_event( VK_NUMLOCK,0x45,KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,0);
    }
}
void main()
{
    SetNumLock( TRUE );
}

4, 已经在VC的AppWizard中选择了中文后如何改为英文?
以某文件编辑器打开资源文件,在其中查找"Language",找到后可看到入下所示:
//Chinese (P.R.C) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)
#ifdef _WIN32
LANGUAGE LANG_CHINESE,SUBLANG_CHINESE_SIMPLIFIED
#pragma code_page(936)
#endif //_WIN32
这段代码表示当前使用的代码页为936,所代表的语种为简体中文,将以下代码用如下代码替换:
//English (U.S) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
#ifdef _WIN32
LANGUAGE LANG_ENGLISH,SUBLANG_ENGLISH_US
#pragma code_page(1252)
#endif //_WIN32

5,如何有效地判断鼠标点是否在控件的矩形区域内
DWORD dw = GetMessagePos();
CPoint pt(LOWORD(dw),HIWORD(dw));//鼠标的屏幕坐标
CRect r;
GetDlgItem(IDC_EDIT1)->GetClientRect(&r);
GetDlgItem(IDC_EDIT1)->ClientToScreen(&r);
if(r.PtInRect(pt))
AfxMessageBox("在控件内");


6,处理控件的右键,类向导上没有
BOOL CCDialogDlg::PreTranslateMessage(MSG* pMsg)
{
    if(WM_MOUSEMOVE == pMsg->message)
    if(pMsg->hwnd == GetDlgItem(IDC_BUTTON1)->GetSafeHwnd())
    {
        UINT nFlag = pMsg->wParam; // 状态,如ctrl是不按下
        int xPos = LOWORD(pMsg->lParam); // horizontal position of cursor
        int yPos = HIWORD(pMsg->lParam); // vertical position of cursor
    }
    return CDialog::PreTranslateMessage(pMsg);
}

VC雕虫小技集(六)
何志丹

1,,如何取得Tree Control上的CheckBox状态~
OnInit中加:
m_treeCtrl.InsertItem("item1");
m_treeCtrl.InsertItem("item2");

void CCDialogDlg::OnButton1()
{
    HTREEITEM hItem = m_treeCtrl.GetRootItem();
    while(NULL != hItem)
    {
        CString str= m_treeCtrl.GetItemText(hItem);
        if("item2" == str)
    {
        if(m_treeCtrl.GetCheck(hItem))
        AfxMessageBox("选中");
    }
    hItem = m_treeCtrl.GetNextVisibleItem(hItem);
    }
}

2,怎么用一个程序向另一个程序发送字符并让其显示出来?
首先通过FindWindow取得windows程序的窗口句柄,然后通过GetDlgItem取得其中输入框的窗口句柄,最后,向该窗口句柄发送WM_CHAR消息即可显示字符
例如,对于Notepad窗口,可以以如下的方式向其中输入一个'a':
取得记事本的窗口句柄
HWND hWnd = ::FindWindow( NULL , "未定标题 - 记事本" );
取得其中输入框的窗口句柄
HWND hEdit = ::GetDlgItem( hWnd , 0x0F ); // 这里0x0F是编辑框的ID,可在SPY++中观察得到
向输入框中填写'a'
::SendMessage( hEdit , WM_CHAR , (WPARAM)'A' , 0x00000001 );

3, 当前时间:
CTime t = CTime::GetCurrentTime();
CString str; str.Format("%d-%d-%d",t.GetYear(),t.GetMonth(),t.GetDay());
str+= t.Format("--%H-%M-%S");
AfxMessageBox(str);
一定要用CTime::GetCurrentTime();GetCurrentTime()是一个过时的函数.


4, //改变按钮的背景色。
HBRUSH CRectWindow2View::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
    HBRUSH hbr = CFormView::OnCtlColor(pDC, pWnd, nCtlColor);
    switch (nCtlColor)
    {
        case CTLCOLOR_BTN:
        {
        CBrush Brush (RGB (128 , 0 , 128) );//你的颜色
        CBrush* pOldBrush = pDC->SelectObject(&Brush);
        pDC->SelectObject (pOldBrush );
        }
    }
    return CFormView::OnCtlColor(pDC, pWnd, nCtlColor);
}

5, 加速键的使用.
在Dlg的头文件中加入:
HACCEL m_hAccel;
在Dlg的构造函数中加载加速键:
基于对话框的程序如何使用加速键?
m_hAccel=::LoadAccelerators(AfxGetInstanceHandle(),MAKEINTRESOURCE(IDR_ACCELERATOR1));//加速键ID
重载PreTranslateMessage函数:
BOOL CDlg::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
if(m_hAccel!=NULL)
if(::TranslateAccelerator(m_hWnd,m_hAccel,pMsg))
return TRUE;
return CDialog::PreTranslateMessage(pMsg);
}

6,怎么把一个文件保存到其它地方?
if(!CopyFile("f://he.txt","d://he1.txt",true))
{
    if(IDOK == MessageBox("有同名文件,你要覆盖吗?",NULL,MB_OKCANCEL))
    {    CopyFile("f://he.txt","d://he1.txt",false);}
}
else
    return;
}

DeleteFile("f://he.txt");

VC雕虫小技集(七)
何志丹

1,图片控件
右键属性 type : bitmap
你直接选image也行
IDB_BITMAP1位图的ID
m_ctrl 是与图片控件相关联的控制型变量
void CDlg2Dlg::OnButton1()
{
    CBitmap bitmap1;
    bitmap1.LoadBitmap(IDB_BITMAP1);
    m_ctrl.SetBitmap(bitmap1);
}
void CDlg2Dlg::OnButton2()
{
    CBitmap bitmap2;
    bitmap2.LoadBitmap(IDB_BITMAP2);
    m_ctrl.SetBitmap(bitmap2);
}

2, 什么我给控件赋变量时看不到cortrol ID?
1,单选按钮,把group钩上.
2,静态控件把ID改成非IDC_STATIC.

3, 大小键盘的ascll码
0-9 不同,但+,-相同.

4,显示键盘输入的字符,尽量避免闪烁
void CSdiView::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
    CDC * pDC = GetDC();
    StringData += nChar;
    CRect r(0,0,0,0);
    pDC->DrawText(StringData,&r,DT_LEFT|DT_CALCRECT);
    InvalidateRect(r);
    CView::OnChar(nChar, nRepCnt, nFlags);
}
void CSdiView::OnDraw(CDC* pDC)
{
    pDC->DrawText(StringData,CRect(0,0,1000,1000),DT_LEFT);
}

5,对话框A domodal()出一个对话框B,点击B一个按钮以后,要求调用A的类中的一个函数。
在b的响应函数中处理:
((A *)GetParent())->fun();
在b中inlcude A所在的文件

6, 删除文件夹及包含的文件
#include
void DeleteDirFile(CString sPath)
{
    WIN32_FIND_DATA fd;
    HANDLE hFind = ::FindFirstFile(sPath + "*.*",&fd);
    if (hFind != INVALID_HANDLE_VALUE)
    {
        while (::FindNextFile(hFind,&fd))
        {
            //判断是否为目录
            if (fd.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
            {
            CString name;
            name = fd.cFileName;
            //判断是否为.和..
            if ((name != ".") && (name != ".."))
            {
            //如果是真正的目录,进行递归
            DeleteDirFile(sPath + fd.cFileName + "//");
            }
        }
    }
    else
        DeleteFile(sPath + fd.cFileName);
   
    ::FindClose(hFind);
    }
    RemoveDirectory(sPath);
}



7, 改变控件字体的大小
LOGFONT logfont;
CFont *pfont = m_ctrShowMessage.GetFont();
pfont->GetLogFont( &logfont );
logfont.lfHeight =logfont.lfHeight * 1.5;
logfont.lfWidth = logfont.lfWidth * 1.5;
CFont font;
font.CreateFontIndirect(&logfont);
m_ctrShowMessage.SetFont(&font);

8, 想用classwizard新建一个类,但发现baseclass一栏中没有我要的基类(CObList类)
class type : Generic
自己输入

9, CTypedPtrList lineList;
为什么VC报错:
c:/程序/scribble/scribbledoc.h(50) : error C2143: syntax error : missing ';' before '<'
# include "afxtempl.h"
是字符 l,不是数字1

10, 不提示成员函数,怎么办?
CString s1="dfdsf";
s1.
试一下以下三种方法:
1, Build->Clean, Build->ReBuildAll.
2,手动删除*.ncb
3,安装辅助工具vc_assist6

11, 我有6个Radio Box如何分成3组
将三个Radio Box的 Group点上
就分成三组了
与焦点顺序有关

原文地址:https://www.cnblogs.com/For-her/p/3915211.html