t;LineTo")]
extern "C" bool LineTo(HDC hDC, int nXEnd, int nYEnd);
// 画线
[DllImport("gdi32", EntryPoint="MoveToEx")]
extern "C" bool MoveTo(HDC hDC, int x, int y, POINT* pt);
// 移动当前位置
}
在鼠标移动事件(MouseMove)处理方法中的主要代码如下:
private: System::Void On_MouseMove(System::Object * sender, System::Windows::Forms::MouseEventArgs * e)
{
……
Graphics *g = this->panel1->CreateGraphics();
// 创建与panel1控件相关联的Graphics
IntPtr hdc = g->GetHdc();
GDI32::HPEN hPen = GDI32::CreatePen( 0, 0, 0xA0A0A0 ); // 创建灰色画笔
GDI32::SelectObject( (GDI32::HDC)hdc, hPen ); // 选入画笔
GDI32::SetROP2( (GDI32::HDC)hdc, 7 ); // 7表示XORPEN模式
GDI32::MoveTo( (GDI32::HDC)hdc, pt.X, pt.Y, NULL );
GDI32::LineTo( (GDI32::HDC)hdc, ptPrev.X, ptPrev.Y );
ptPrev = Point( e->X, e->Y );
GDI32::MoveTo( (GDI32::HDC)hdc, pt.X, pt.Y, NULL );
GDI32::LineTo( (GDI32::HDC)hdc, ptPrev.X, ptPrev.Y );
g->ReleaseHdc( hdc );
}
图1 GDI+和GDI混合编程实例
4.调用MFC DLL封装的GDI
通过平台调用可以在托管C++中使用GDI API,但代码有时比较繁琐。事实上,还可以使用MFC DLL[6]来封装GDI API,然后再通过平台调用,则显得比较简洁。例如,创建一个扩展MFC DLL应用程序MFCGDIDLL,在MFCGDIDLL.cpp文件的最后添加下列代码:
extern "C" __declspec(dllexport)
void DrawGDIXorSolidLine( HDC hDC, DWORD color, int nWidth, int x1, int y1, int x2, int y2 )
{
HPEN pen = ::CreatePen( 0, nWidth, color );
HPEN oldPen = (HPEN)::SelectObject( hDC, pen );
int nOldDrawMode = ::SetROP2( hDC, R2_XORPEN );
::MoveToEx( hDC, x1, y1, NULL );
::LineTo( hDC, x2, y2 );
::SelectObject( hDC, oldPen );
::SetROP2( hDC, nOldDrawMode );
}
然后将编译后的mfcgdidll.dll复制到前面实例中的项目文件夹中,并添加下列平台调用的函数代码:
namespace MFCGDI
{
using namespace System;
using namespace System::Runtime::InteropServices;
typedef void* HDC;
[DllImport("mfcgdidll", EntryPoint="DrawGDIXorSolidLine")]
extern "C" void DrawGDIXorSolidLine( HDC hdc, unsigned long color,
int nWidth, int x1, int y1, int x2, int y2);
}
最后修改前面实例中的鼠标移动事件(MouseMove)处理方法中的代码:
private: System::Void On_MouseMove(System::Object * sender, System::Windows::Forms::MouseEventArgs * e)
{
……
Graphics *g = this->panel1->CreateGraphics();
// 创建与panel1控件相关联的Graphics
IntPtr hdc = g->GetHdc();
MFCGDI::DrawGDIXorSolidLine( (MFCGDI::HDC)hdc,
0xA0A0A0, 1, pt.X, pt.Y, ptPrev.X, ptPrev.Y );
ptPrev = Point( e->X, e->Y );
MFCGDI::DrawGDIXorSolidLine( (MFCGDI::HDC)hdc,
0xA0A0A0, 1, pt.X, pt.Y, ptPrev.X, ptPrev.Y );
g->ReleaseHdc( hdc );
}
5.结语
Visual C++.NET中,虽然MFC和托管C++均可以使用.NET框架中的GDI+,但托管C++专为Visual C++程序员开发.NET框架应用程序而设计,它除了保留标准C++的全部功能,还可通过.NET Framework(.NET框架)来创建对象,实现自动化内存管理以及与其他.NET语言的互操 |