VC++ 从View类获取各种指针编程实例

新建一个多文档工程;名为GetPtrDemo;

在视类OnDraw函数,获取其他类指针;然后进行一些操作;

首先获取应用程序类指针;可以获取到;然后利用它输出程序名;

    CGetPtrDemoApp* pApp=(CGetPtrDemoApp*)AfxGetApp();
    pDC->TextOut(100,10, pApp->m_pszAppName);

然后获取主框架类指针;直接在视类OnDraw函数加入如下代码,编译会出现

error C2065: 'CMainFrame' : undeclared identifier;

因为一般不需要直接在视类获取主框架指针;    
    CMainFrame* pMainFrame = (CMainFrame*)(AfxGetApp()->m_pMainWnd);
    pDC->TextOut(100,40, (void*)pMainFrame);
    CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
    

获取菜单指针;输出指针的值;获取第一个菜单的文本,然后输出;可以;
    CMenu* pMenu = AfxGetMainWnd()->GetMenu();
    pDC->TextOut(100,40, (char*)pMenu);
    CString strmenu1;
    pMenu->GetMenuString(1,strmenu1,MF_BYPOSITION);
    pDC->TextOut(100,70, strmenu1);

获取工具条指针;然后获取第一个按钮的文本,设置第四个按钮的文本;获取不到第一个按钮的文本,设置也无效;可能是按钮风格方面的一些问题;下回再搞;

    CToolBar* pToolBar = (CToolBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR);
    CString strtooltext;
    pToolBar->GetButtonText(1,strtooltext);
    pToolBar->SetButtonText(4,"我自己改的");
    pDC->TextOut(100,100, strtooltext);

    //CStatusBar* pStatusBar = (CStatusBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR);

获取文档指针;视类OnDraw函数已经具有该指针;可直接使用;输出文档标题;

    pDC->TextOut(100,150,pDoc->GetTitle());

OnDraw函数如下;

void CGetPtrDemoView::OnDraw(CDC* pDC)
{
	CGetPtrDemoDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);
	// TODO: add draw code for native data here
	CGetPtrDemoApp* pApp=(CGetPtrDemoApp*)AfxGetApp();
	pDC->TextOut(100,10, pApp->m_pszAppName);
	
	//CMainFrame* pMainFrame = (CMainFrame*)(AfxGetApp()->m_pMainWnd);
	//pDC->TextOut(100,40, (void*)pMainFrame);
	//CMainFrame* pMainFrame = (CMainFrame*)AfxGetMainWnd();
	
	CMenu* pMenu = AfxGetMainWnd()->GetMenu();
	pDC->TextOut(100,40, (char*)pMenu);
	CString strmenu1;
	pMenu->GetMenuString(1,strmenu1,MF_BYPOSITION);
	pDC->TextOut(100,70, strmenu1);

	CToolBar* pToolBar = (CToolBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_TOOLBAR);
	CString strtooltext;
	pToolBar->GetButtonText(1,strtooltext);
	pToolBar->SetButtonText(4,"我自己改的");
	pDC->TextOut(100,100, strtooltext);

	//CStatusBar* pStatusBar = (CStatusBar*)AfxGetMainWnd()->GetDescendantWindow(AFX_IDW_STATUS_BAR);

	pDC->TextOut(100,150,pDoc->GetTitle());
}

运行截图:

猜你喜欢

转载自blog.csdn.net/bcbobo21cn/article/details/88781674
今日推荐