Thanks to gile and Kerry.Job is done! This is the codes.Using a SelectCrossingWindow to reduse the number of entitier.
public static void UseCrossingWindow()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Database db = doc.Database;
Editor ed = doc.Editor;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
PromptPointResult ppr = ed.GetPoint("\n Sepecify the first Point:");
if (ppr.Status != PromptStatus.OK) return;
Point3d pt1 = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);
//Get another point to form a SeltectCrossingWindow
ppr = ed.GetPoint("\n Sepecify the second Point:");
if (ppr.Status != PromptStatus.OK) return;
Point3d pt2 = ppr.Value.TransformBy(ed.CurrentUserCoordinateSystem);
// Create a crossing window based on the two selected points
PromptSelectionResult acSSPrompt;
acSSPrompt = ed.SelectCrossingWindow(pt1, pt2);
// If the prompt status is not OK, do nothing.
if (acSSPrompt.Status != PromptStatus.OK)
return;
SelectionSet acSSet = acSSPrompt.Value;
ObjectId[] ids = acSSet.GetObjectIds();
Line closest = null;
double shortest = 0.0;
foreach (ObjectId id in ids)
{
Line line = trans.GetObject(id, OpenMode.ForRead) as Line;
if (line != null)
{
double dist = pt1.DistanceTo(line.GetClosestPointTo(pt1, false));
if (dist == 0)
continue;
if (closest == null)
{
closest = line;
shortest = dist;
}
else if (shortest > dist)
{
closest = line;
shortest = dist;
}
}
}
if (closest != null)
{
closest.Highlight();
ed.WriteMessage("\nDistance = {0}", shortest);
}
/*
double shortest = 0.0;
foreach (ObjectId id in ids)
{
Entity ent = (Entity)trans.GetObject(id, OpenMode.ForWrite);
if (ent.GetType().Name == "Line")
{
Line myLine = (Line)trans.GetObject(id, OpenMode.ForWrite);
double dist = pt1.DistanceTo(myLine.GetClosestPointTo(pt1,false));
if (dist!=0 && shortest > dist)
{
shortest = dist;
}
}
} //End of foreach loop
ed.WriteMessage("\nDistance = {0}", shortest);
*/
trans.Commit();
}
}
By the way.The codes which have be commented out don't work. The result is "0".
And another question,how to rule out other kinds of entities when define the SelectCrossingWindow?
Hoping it will be helpful someone else!