初始化时将地图控件MapControl传进来,绘制过程中监听鼠标操作事件,适情况隐藏父级窗体,绘制点、多段线、多边形、圆形、矩形等。
public class DrawGeometryHelper
{
private IMapControl2 m_pMapControl;
private IntPtr m_hWnd;
public DrawGeometryHelper()
{
}
public DrawGeometryHelper(IMapControl2 mapControl, IntPtr? hWnd)
{
Init(mapControl, hWnd);
}
public void Init(IMapControl2 mapControl, IntPtr? hWnd)
{
m_pMapControl = mapControl;
if (hWnd != null)
{
m_hWnd = (IntPtr)hWnd;
}
}
private POINT GetMouseDownPoint(int hWnd = 0)
{
POINT pt = new POINT();
while (true)
{
bool b = false;
var msg = new MSG();
while (PeekMessage(ref msg, hWnd, 0x201, 0x203, PeekMessageOption.PM_REMOVE))
{
if (msg.Message == 0x201)
{
if (GetCursorPos(out pt) && pt.X > 0 && pt.Y > 0)
{
b = true;
break;
}
}
TranslateMessage(ref msg);
DispatchMessage(ref msg);
}
if (b)
break;
}
return pt;
}
public IGeometry Draw(DrawTypeEnum drawType = DrawTypeEnum.Polygon, double buffer = 0.0, bool hideWindow = true)
{
if (null == m_pMapControl) return null;
var bHide = false;
if (hideWindow && null != m_hWnd)
{
bHide = Win32ApiFormProc.ShowWindow(m_hWnd, Win32ApiFormProc.SW_HIDE);
}
var originalTool = m_pMapControl.CurrentTool;
var originalMoustPointer = m_pMapControl.MousePointer;
m_pMapControl.CurrentTool = null;
m_pMapControl.MousePointer = esriControlsMousePointer.esriPointerPencil;
var point = GetMouseDownPoint();
IGeometry pGeometry = null;
switch (drawType)
{
case DrawTypeEnum.Point:
{
pGeometry = m_pMapControl.ToMapPoint(point.X, point.Y);
break;
}
case DrawTypeEnum.Polyline:
{
pGeometry = m_pMapControl.TrackLine();
break;
}
case DrawTypeEnum.Polygon:
{
pGeometry = m_pMapControl.TrackPolygon();
break;
}
case DrawTypeEnum.Rectangle:
{
pGeometry = m_pMapControl.TrackRectangle();
break;
}
case DrawTypeEnum.Circle:
{
pGeometry = m_pMapControl.TrackCircle();
break;
}
default:
break;
}
m_pMapControl.CurrentTool = originalTool;
m_pMapControl.MousePointer = originalMoustPointer;
if (null != pGeometry)
{
m_pMapControl.FlashShape(pGeometry);
}
if (bHide)
{
Win32ApiFormProc.ShowWindow(m_hWnd, Win32ApiFormProc.SW_SHOW);
}
return pGeometry;
}
}
其中,ShowWindow方法为从user32.dll中导入:
[DllImport("user32.dll", EntryPoint = "ShowWindow")]
public static extern bool ShowWindow(IntPtr hwnd, int nCmdShow);
绘制类型枚举如下:
public enum DrawTypeEnum
{
Point = 0,
Polyline = 1,
Polygon = 2,
Rectangle = 3,
Circle = 4
}