用C#和ArcGIS Engine實現在地圖上繪製形狀
阿新 • • 發佈:2018-12-04
初始化時將地圖控制元件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
}