本文要求讀者熟悉 C#
開發環境: Visual Studio .NET 2003 Windows 2000
測試環境:Windows 2000
更新記錄:2004.4.7 第一次更新
使用許可:代碼是否免費使用
功能介紹:
在MFC中CRectTracker是一個很有用的類,可最近學習C#時,發現沒有,於是就從MFC轉換了一個供大家享用。
使用該類比較簡單,幾乎和 MFC中 的 CRectTracker 一樣,在MDI中:
public class CReportDoc
{ ...
public CRectTracker m_tracker=null;
public CReportDoc(MainWindow mainWin)
{ ...
m_tracker=new CRectTracker();
m_tracker.m_rect.X = 10;
m_tracker.m_rect.Y = 10;
m_tracker.m_rect.Width = 91;
m_tracker.m_rect.Height = 91;
...
}
...
}
相應的在VIEW類裡面
public class CReportView : System.Windows.Forms.Form
{
...
private void InitializeComponent()
{
...
this.MouseDown +=
new System.Windows.Forms.MouseEventHandler(this.CReportView_MouseDown);
this.Paint +=
new System.Windows.Forms.PaintEventHandler(this.PaintHandler);
// 因為C#中不支持OnSetCursor所以只好用MouseMove替代了,
// 各位兄台還有更好的方法,請告之
this.MouseMove+=new MouseEventHandler(CReportView_MouseMove);
}
private void PaintHandler(Object sender, PaintEventArgs e)
{
Graphics gs=e.Graphics;
//其余的畫圖代碼
myDoc.m_tracker.OnDraw(gs);
}
private void CReportView_MouseDown(object sender,
MouseEventArgs e)
{
if(e.Button==MouseButtons .Left)
{
Rectangle rectSave=new Rectangle();
Point pt=new Point(e.X,e.Y);
myDoc.m_tracker.GetTrueRect(ref rectSave);
if (myDoc.m_tracker.HitTest(pt) < 0)
{ // just to demonstrate CRectTracker::TrackRubberBand
CRectTracker tracker=new CRectTracker();
if (tracker.TrackRubberBand(this,
pt,
myDoc.m_bAllowInvert))
{ // see if rubber band intersects with the doc''s tracker
tracker.NormalizeRect(ref tracker.m_rect);
// so intersect rect works
if (tracker.m_rect.IntersectsWith(myDoc.m_tracker.m_rect))
{ // if so, put resize handles on it (ie. select it)
if ((myDoc.m_tracker.m_nStyle &
CRectTracker.StyleFlags.resizeInside)!=0)
{ // swap from resize inside to
// resize outside for effect
myDoc.m_tracker.m_nStyle &=
~CRectTracker.StyleFlags.resizeInside;
myDoc.m_tracker.m_nStyle |=
CRectTracker.StyleFlags.resizeOutside;
}
else
{// just use inside resize handles on first time
myDoc.m_tracker.m_nStyle &=
~CRectTracker.StyleFlags.resizeOutside;
myDoc.m_tracker.m_nStyle |=
CRectTracker.StyleFlags.resizeInside;
}
}
}
myDoc.UpdateAllViews(null);
}
}
else
{
if (myDoc.m_tracker.Track(this,
pt,
myDoc.m_bAllowInvert,null))
{
// normal tracking action, when tracker is "hit"
myDoc.UpdateAllViews(null);
}
}
}
private void CReportView_MouseMove(object sender, MouseEventArgs e)
{
Point mousept=new Point(e.X,e.Y);
if(!myDoc.m_tracker.SetCursor(this,0,mousept))
this.Cursor=Cursors.Arrow;
}
...
}
結束。