VC++6获取屏幕以及控制台的CDC对象
获取屏幕的CDC对象
CDC* GetScreenDC()
{
HDC hDC = CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL);
CDC* ret = new CDC();
ret->Attach(hDC);
return ret;
}
CreateDC函数声明是HDC CreateDC(LPCTSTR lpszDrive, LPCTSTR lpszDevice, LPCTSTR lpszOutput, CONST DEVMODE *lplnitData);
,作用是获取指定设备上下文。当lpszDevice为DISPLAY时,其它参数必须是NULL,此时返回屏幕的设备上下文。
获取屏幕以及控制台的CDC对象
CDC* GetConsoleDC()
{
HWND hWnd = GetConsoleWindow();
HDC hDC = GetDC(hWnd);
CDC* ret = new CDC();
ret->Attach(hDC);
return ret;
}
HWND GetConsoleWindow();
返回控制台窗体对象,HDC GetDC(HWND hWnd);
根据指定窗体对象返回窗体设备上下文。
实例
在Visual C++6.0中创建一个支持MFC的Win32控制台应用程序,名称为DC,在主程序DC.cpp中,代码改为如下
// DC.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "DC.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern "C" WINBASEAPI HWND WINAPI GetConsoleWindow ();
/
// The one and only application object
CWinApp theApp;
using namespace std;
CDC* GetScreenDC()
{
HDC hDC = CreateDC(TEXT("DISPLAY"),NULL,NULL,NULL);
CDC* ret = new CDC();
ret->Attach(hDC);
return ret;
}
CDC* GetConsoleDC()
{
HWND hWnd = GetConsoleWindow();
HDC hDC = GetDC(hWnd);
CDC* ret = new CDC();
ret->Attach(hDC);
return ret;
}
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
// initialize MFC and print and error on failure
if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
cerr << _T("Fatal Error: MFC initialization failed") << endl;
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
CPen m_pen(PS_SOLID,2,RGB(255,0,0));
CDC* m_screen = GetScreenDC();
m_screen->SelectObject(m_pen);
m_screen->Arc(0,0,500,500,0,250,0,250);
CDC* m_console = GetConsoleDC();
m_console->SelectObject(m_pen);
m_console->Arc(30,30,80,80,0,55,0,55);
delete m_screen;
delete m_console;
nRetCode = 0;
}
return nRetCode;
}
extern "C" WINBASEAPI HWND WINAPI GetConsoleWindow ();
是为了防止VC++6找不到GetConsoleWindow ()函数。
运行结果如下