02-08 控制AutoCAD環境(八) 提示用戶輸入

 

Prompt for User Input  提示用戶輸入

The Editor object, which is a child of the Document object, defines the user input methods. The user input methods display a prompt on the AutoCAD command line or in a dynamic input tooltip, and request input of various types. This type of user input is most useful for interactive input of screen coordinates, entity selection, and short-string or numeric values. If your application requires the input of numerous options or values, a Windows form may be more appropriate than individual prompts.

用戶輸入方法由Document對象的派生類Editor對象定義。用戶輸入方法在AutoCAD命令行或動態輸入提示框裏顯示一個提示,請求各種不同類型的輸入。這種用戶輸入在交互輸入屏幕座標、實體選擇、短字串及數值時特別有用。如果程序需要輸入多個選項或值時,用Windows窗口比單個單個的提示更合適。

Each user input method displays an optional prompt on the command line and returns a value specific to the type of input requested. For example, GetString returns a PromptResult which allows you to determine the status of the GetString method and retrieve the string the user entered. Each one of the user input methods has a specific return value.

每個用戶輸入方法都在命令行顯示可選提示並返回一個輸入所需類型的值。例如,GetString方法返回一個PromptResult類型的值,該值允許我們確定GetString方法的狀態並取回用戶所輸入的值。每個用戶輸入方法都有與之相應的返回值。

The input methods accept a string for the prompt message to be displayed or a specific object type which controls the input from the user. These object types let you control things such as NULL input (pressing Enter), base point, input of zero or negative numbers, and input of arbitrary text values.

輸入方法接受一個字符串用來顯示提示信息,或接受一個指定對象類型來控制來自用戶的輸入。這些對象類型用來控制諸如NULL輸入(按了Enter鍵)、基點、輸入了0或負數、亂七八糟的文本輸入等情況。

To force the prompt to be displayed on a line by itself, use the carriage return/linefeed constant (vbCrLf) or linefeed constant (vbLf) at the beginning of your prompt strings when using VB.NET, or "\n" with strings in C#.

要強制提示顯示在單獨一行上,使用VB.NET時可以在提示字符串開頭加上回車/換行常量(vbCrLf)或換行常量(vbLf),用C#的話就在字符串前加上“\n”。

Topics in this section本節主題

·         GetString Method   GetString方法

·         GetPoint Method   GetPoint方法

·         GetKeywords Method   GetKeywords方法

·         Control User Input   控制用戶輸入

 

1、GetString Method  GetString方法

The GetString method prompts the user for the input of a string at the Command prompt. The PromptStringOptions object allows you to control the input entered and how the prompt message appears. The AllowSpaces property of the PromptStringOptions object controls if spaces are allowed or not at the prompt. If set to false, pressing the Spacebar terminates the input.

GetString方法提示用戶在Command提示光標處輸入一個字符串。PromptStringOptions對象用來控制鍵入的輸入及提示信息呈現方式。PromptStringOptions對象的AllowSpaces屬性控制提示是否可以輸入空格,如果設置爲false,按空格鍵就終止輸入。

Get a string value from the user at the AutoCAD command line 在AutoCAD命令行獲取用戶輸入的字符串

The following example displays the Enter Your Name prompt, and requires that the input from the user be terminated by pressing Enter (spaces are allowed in the input string). The entered string is displayed in a message box.

下面例子顯示“Enter Your Name”的提示,並要求用戶按Enter鍵完成輸入(允許輸入空格)。輸入的字符串顯示在消息框內。

VB.NET

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.EditorInput

Imports Autodesk.AutoCAD.Runtime

 

<CommandMethod("GetStringFromUser")> _

Public Sub GetStringFromUser()

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

 

  Dim pStrOpts As PromptStringOptions = New PromptStringOptions(vbLf & _

                                                               "Enter your name: ")

  pStrOpts.AllowSpaces = True

  Dim pStrRes As PromptResult = acDoc.Editor.GetString(pStrOpts)

 

  Application.ShowAlertDialog("The name entered was: " & _

                              pStrRes.StringResult)

End Sub

C#

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

 

[CommandMethod("GetStringFromUser")]

public static void GetStringFromUser()

{

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

 

  PromptStringOptions pStrOpts = new PromptStringOptions("\nEnter your name: ");

  pStrOpts.AllowSpaces = true;

  PromptResult pStrRes = acDoc.Editor.GetString(pStrOpts);

 

  Application.ShowAlertDialog("The name entered was: " +

                              pStrRes.StringResult);

}

VBA/ActiveX Code Reference

Sub GetStringFromUser()

    Dim retVal As String

    retVal = ThisDrawing.Utility.GetString _

                                    (1, vbCrLf & "Enter your name: ")

    MsgBox "The name entered was: " & retVal

End Sub

 

2、GetPoint Method  GetPoint方法

The GetPoint method prompts the user to specify a point at the Command prompt. The PromptPointOptions object allows you to control the input entered and how the prompt message appears. The UseBasePoint and BasePoint properties of the PromptPointOptions object controls if a rubber-band line is drawn from a base point. The Keywords property of the PromptPointOptions object allows you to define keywords that can be entered at the Command prompt in addition to specifying a point.

GetPoint方法提示用戶在Command提示時指定一個點。PromptPointOptions對象用來控制鍵入的輸入及提示信息呈現方式。PromptPointOptions對象的UseBasePoint屬性和BasePoint屬性控制是否從基點繪製一條橡皮帶線。PromptPointOptions對象的Keywords屬性用來定義除了指定點外還可以在Command提示光標處輸入的關鍵字。

Get a point selected by the user 獲取用戶選取的點

The following example prompts the user for two points, then draws a line using those points as the start point and endpoint.

下例提示用戶選取兩個點,然後喲個這兩個點作爲起止點畫一條線。

VB.NET

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.DatabaseServices

Imports Autodesk.AutoCAD.EditorInput

Imports Autodesk.AutoCAD.Geometry

Imports Autodesk.AutoCAD.Runtime

<CommandMethod("GetPointsFromUser")> _

Public Sub GetPointsFromUser()

  '' Get the current database and start the Transaction Manager

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim acCurDb As Database = acDoc.Database

  Dim pPtRes As PromptPointResult

  Dim pPtOpts As PromptPointOptions = New PromptPointOptions("")

  '' Prompt for the start point

  pPtOpts.Message = vbLf & "Enter the start point of the line: "

  pPtRes = acDoc.Editor.GetPoint(pPtOpts)

  Dim ptStart As Point3d = pPtRes.Value

  '' Exit if the user presses ESC or cancels the command

  If pPtRes.Status = PromptStatus.Cancel Then Exit Sub

  '' Prompt for the end point

  pPtOpts.Message = vbLf & "Enter the end point of the line: "

  pPtOpts.UseBasePoint = True

  pPtOpts.BasePoint = ptStart

  pPtRes = acDoc.Editor.GetPoint(pPtOpts)

  Dim ptEnd As Point3d = pPtRes.Value

  If pPtRes.Status = PromptStatus.Cancel Then Exit Sub

  '' Start a transaction

  Using acTrans As Transaction = acCurDb.TransactionManager.StartTransaction()

      Dim acBlkTbl As BlockTable

      Dim acBlkTblRec As BlockTableRecord

      '' Open Model space for write

      acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId, _

                                   OpenMode.ForRead)

      acBlkTblRec = acTrans.GetObject(acBlkTbl(BlockTableRecord.ModelSpace), _

                                      OpenMode.ForWrite)

      '' Define the new line

      Dim acLine As Line = New Line(ptStart, ptEnd)

      '' Add the line to the drawing

      acBlkTblRec.AppendEntity(acLine)

      acTrans.AddNewlyCreatedDBObject(acLine, True)

      '' Zoom to the extents or limits of the drawing

      acDoc.SendStringToExecute("._zoom _all ", True, False, False)

      '' Commit the changes and dispose of the transaction

      acTrans.Commit()

  End Using

End Sub

C#

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.DatabaseServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Geometry;

using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetPointsFromUser")]

public static void GetPointsFromUser()

{

  // Get the current database and start the Transaction Manager

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  Database acCurDb = acDoc.Database;

  PromptPointResult pPtRes;

  PromptPointOptions pPtOpts = new PromptPointOptions("");

  // Prompt for the start point

  pPtOpts.Message = "\nEnter the start point of the line: ";

  pPtRes = acDoc.Editor.GetPoint(pPtOpts);

  Point3d ptStart = pPtRes.Value;

  // Exit if the user presses ESC or cancels the command

  if (pPtRes.Status == PromptStatus.Cancel) return;

  // Prompt for the end point

  pPtOpts.Message = "\nEnter the end point of the line: ";

  pPtOpts.UseBasePoint = true;

  pPtOpts.BasePoint = ptStart;

  pPtRes = acDoc.Editor.GetPoint(pPtOpts);

  Point3d ptEnd = pPtRes.Value;

  if (pPtRes.Status == PromptStatus.Cancel) return;

  // Start a transaction

  using (Transaction acTrans = acCurDb.TransactionManager.StartTransaction())

  {

      BlockTable acBlkTbl;

      BlockTableRecord acBlkTblRec;

      // Open Model space for write

      acBlkTbl = acTrans.GetObject(acCurDb.BlockTableId,  OpenMode.ForRead) as BlockTable;

      acBlkTblRec = acTrans.GetObject(acBlkTbl[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;

      // Define the new line

      Line acLine = new Line(ptStart, ptEnd);

      // Add the line to the drawing

      acBlkTblRec.AppendEntity(acLine);

      acTrans.AddNewlyCreatedDBObject(acLine, true);

      // Zoom to the extents or limits of the drawing

      acDoc.SendStringToExecute("._zoom _all ", true, false, false);

      // Commit the changes and dispose of the transaction

      acTrans.Commit();

  }

}

VBA/ActiveX Code Reference

Sub GetPointsFromUser()

    Dim startPnt As Variant

    Dim endPnt As Variant

    Dim prompt1 As String

    Dim prompt2 As String

    prompt1 = vbCrLf & "Enter the start point of the line: "

    prompt2 = vbCrLf & "Enter the end point of the line: "

    ' Get the first point without entering a base point

    startPnt = ThisDrawing.Utility.GetPoint(, prompt1)

    ' Use the point entered above as the base point

    endPnt = ThisDrawing.Utility.GetPoint(startPnt, prompt2)

    ' Create a line using the two points entered

    ThisDrawing.ModelSpace.AddLine startPnt, endPnt

    ThisDrawing.Application.ZoomAll

End Sub

  

3、GetKeywords Method  GetKeywords方法

The GetKeywords method prompts the user for input of a keyword at the Command prompt. The PromptKeywordOptions object allows you to control the input entered and how the prompt message appears. The Keywords property of the PromptKeywordOptions object allows you to define keywords that can be entered at the Command prompt.

GetKeywords方法提示用戶在Command提示光標處輸入一個關鍵字PromptKeywordOptions對象用來控制鍵入及提示信息呈現方式。PromptKeywordOptions對象的Keywords屬性用來定義可在Command提示光標處鍵入的關鍵字。

Get a keyword from the user at the AutoCAD command line 從AutoCAD命令行獲取用戶輸入的關鍵字

The following example forces the user to enter a keyword by setting the property AllowNone to false, which disallows NULL input (pressing Enter). The Keywords property is used to add the valid keywords allowed.

下例將PromptKeywordOptions對象的AllowNone屬性設置爲false(不允許直接回車),這樣使用戶必須輸入一個關鍵字。Keywords屬性用來添加允許的合法關鍵字。

VB.NET

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.EditorInput

Imports Autodesk.AutoCAD.Runtime

<CommandMethod("GetKeywordFromUser")> _

Public Sub GetKeywordFromUser()

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim pKeyOpts As PromptKeywordOptions = New PromptKeywordOptions("")

  pKeyOpts.Message = vbLf & "Enter an option "

  pKeyOpts.Keywords.Add("Line")

  pKeyOpts.Keywords.Add("Circle")

  pKeyOpts.Keywords.Add("Arc")

  pKeyOpts.AllowNone = False

  Dim pKeyRes As PromptResult = acDoc.Editor.GetKeywords(pKeyOpts)

  Application.ShowAlertDialog("Entered keyword: " &  pKeyRes.StringResult)

End Sub

C#

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetKeywordFromUser")]

public static void GetKeywordFromUser()

{

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");

  pKeyOpts.Message = "\nEnter an option ";

  pKeyOpts.Keywords.Add("Line");

  pKeyOpts.Keywords.Add("Circle");

  pKeyOpts.Keywords.Add("Arc");

  pKeyOpts.AllowNone = false;

   PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

  Application.ShowAlertDialog("Entered keyword: " +  pKeyRes.StringResult);

}

VBA/ActiveX Code Reference

Sub GetKeywordFromUser()

    Dim keyWord As String

    ThisDrawing.Utility.InitializeUserInput 1, "Line Circle Arc"

    keyWord = ThisDrawing.Utility.GetKeyword _

              (vbCrLf & "Enter an option [Line/Circle/Arc]: ")

    MsgBox keyWord, , "GetKeyword Example"

End Sub

A more user-friendly keyword prompt is one that provides a default value if the user presses Enter (NULL input). Notice the minor modifications to the following example.

更用戶友好的關鍵字提示方式是如果用戶按Enter鍵(沒有輸入)時提供一個缺省值。注意下面的這個小小改動。

VB.NET

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.EditorInput

Imports Autodesk.AutoCAD.Runtime

<CommandMethod("GetKeywordFromUser2")> _

Public Sub GetKeywordFromUser2()

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim pKeyOpts As PromptKeywordOptions = New PromptKeywordOptions("")

  pKeyOpts.Message = vbLf & "Enter an option "

  pKeyOpts.Keywords.Add("Line")

  pKeyOpts.Keywords.Add("Circle")

  pKeyOpts.Keywords.Add("Arc")

  pKeyOpts.Keywords.Default = "Arc"

  pKeyOpts.AllowNone = True

  Dim pKeyRes As PromptResult = acDoc.Editor.GetKeywords(pKeyOpts)

  Application.ShowAlertDialog("Entered keyword: " &  pKeyRes.StringResult)

End Sub

C#

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetKeywordFromUser2")]

public static void GetKeywordFromUser2()

{

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  PromptKeywordOptions pKeyOpts = new PromptKeywordOptions("");

  pKeyOpts.Message = "\nEnter an option ";

  pKeyOpts.Keywords.Add("Line");

  pKeyOpts.Keywords.Add("Circle");

  pKeyOpts.Keywords.Add("Arc");

  pKeyOpts.Keywords.Default = "Arc";

  pKeyOpts.AllowNone = true;

  PromptResult pKeyRes = acDoc.Editor.GetKeywords(pKeyOpts);

  Application.ShowAlertDialog("Entered keyword: " + pKeyRes.StringResult);

}

VBA/ActiveX Code Reference

Sub GetKeywordFromUser2()

    Dim keyWord As String

    ThisDrawing.Utility.InitializeUserInput 0, "Line Circle Arc"

    keyWord = ThisDrawing.Utility.GetKeyword _

              (vbCrLf & "Enter an option [Line/Circle/Arc] <Arc>: ")

    If keyWord = "" Then keyWord = "Arc"

    MsgBox keyWord, , "GetKeyword Example"

End Sub

 

4、Control User Input  控制用戶輸入

When collecting input from the user, you want to make sure you limit the type of information they can enter so you can get the desired response. The various prompt option objects are used to not only define the prompt displayed at the Command prompt, but also restrict the input that the user can provide. With some of the input methods, not only can you get a return value based on the type of method used but also get a keyword.

當收集用戶輸入時,我們要確保能夠限制用戶輸入信息的類型,這樣我們就可以得到我們想要的迴應。使用各種不同的提示選項對象,不僅可以定義Command提示上顯示的提示信息,而且可以限制用戶的輸入。使用有些輸入方法,我們不僅可以獲得基於方法所用類型的返回值,而且還可以獲得關鍵字。

For example, you can use the GetPoint method to have the user specify a point or respond with a keyword. This is how commands like LINE, CIRCLE, and PLINE work.

例如我們可以使用GetPoint方法讓用戶指定一個點或迴應以一個關鍵字,就像使用LINE、CIRCLE及PLINE這樣的命令那樣。

Get an integer value or a keyword 獲取一個整數或一個關鍵字

The following example prompts the user for a positive non-zero integer value or a keyword.

下例提示用戶輸入一個非零的正整數或一個關鍵字。

VB.NET

Imports Autodesk.AutoCAD.ApplicationServices

Imports Autodesk.AutoCAD.EditorInput

Imports Autodesk.AutoCAD.Runtime

<CommandMethod("GetIntegerOrKeywordFromUser")> _

Public Sub GetIntegerOrKeywordFromUser()

  Dim acDoc As Document = Application.DocumentManager.MdiActiveDocument

  Dim pIntOpts As PromptIntegerOptions = New PromptIntegerOptions("")

  pIntOpts.Message = vbCrLf & "Enter the size or "

  '' Restrict input to positive and non-negative values

  pIntOpts.AllowZero = False

  pIntOpts.AllowNegative = False

  '' Define the valid keywords and allow Enter

  pIntOpts.Keywords.Add("Big")

  pIntOpts.Keywords.Add("Small")

  pIntOpts.Keywords.Add("Regular")

  pIntOpts.Keywords.Default = "Regular"

  pIntOpts.AllowNone = True

  '' Get the value entered by the user

  Dim pIntRes As PromptIntegerResult = acDoc.Editor.GetInteger(pIntOpts)

  If pIntRes.Status = PromptStatus.Keyword Then

      Application.ShowAlertDialog("Entered keyword: " & pIntRes.StringResult)

  Else

      Application.ShowAlertDialog("Entered value: " &  pIntRes.Value.ToString())

  End If

End Sub

C#

using Autodesk.AutoCAD.ApplicationServices;

using Autodesk.AutoCAD.EditorInput;

using Autodesk.AutoCAD.Runtime;

[CommandMethod("GetIntegerOrKeywordFromUser")]

public static void GetIntegerOrKeywordFromUser()

{

  Document acDoc = Application.DocumentManager.MdiActiveDocument;

  PromptIntegerOptions pIntOpts = new PromptIntegerOptions("");

  pIntOpts.Message = "\nEnter the size or ";

  // Restrict input to positive and non-negative values

  //限制輸入必須大於0;

  pIntOpts.AllowZero = false;

  pIntOpts.AllowNegative = false;

  // Define the valid keywords and allow Enter

  //定義合法關鍵字並允許直接按Enter鍵;

  pIntOpts.Keywords.Add("Big");

  pIntOpts.Keywords.Add("Small");

  pIntOpts.Keywords.Add("Regular");

  pIntOpts.Keywords.Default = "Regular";

  pIntOpts.AllowNone = true;

  // Get the value entered by the user

  //獲取用戶鍵入的值

  PromptIntegerResult pIntRes = acDoc.Editor.GetInteger(pIntOpts);

  if (pIntRes.Status == PromptStatus.Keyword)

  {

      Application.ShowAlertDialog("Entered keyword: " +  pIntRes.StringResult);

  }

  else

  {

      Application.ShowAlertDialog("Entered value: " +  pIntRes.Value.ToString());

  }

}

VBA/ActiveX Code Reference

Sub GetIntegerOrKeywordFromUser()

    ' The first parameter of InitializeUserInput (6)

    ' restricts input to positive and non-negative

    ' values. The second parameter is the list of

    ' valid keywords.

    ThisDrawing.Utility.InitializeUserInput 6, "Big Small Regular"

    ' Set the prompt string variable

    Dim promptStr As String

    promptStr = vbCrLf & "Enter the size or [Big/Small/Regular] <Regular>:"

    ' At the GetInteger prompt, entering a keyword or pressing

    ' ENTER without entering a value results in an error. To allow

    ' your application to continue and check for the error

    ' description, you must set the error handler to resume on error.

    On Error Resume Next

    ' Get the value entered by the user

    Dim returnInteger As Integer

    returnInteger = ThisDrawing.Utility.GetInteger(promptStr)

    ' Check for an error. If the error number matches the

    ' one shown below, then use GetInput to get the returned

    ' string; otherwise, use the value of returnInteger.

    If Err.Number = -2145320928 Then

        Dim returnString As String

        Debug.Print Err.Description

        returnString = ThisDrawing.Utility.GetInput()

        If returnString = "" Then        'ENTER returns null string

           returnString = "Regular"     'Set to default

        End If

        Err.Clear

    Else 'Otherwise,

        returnString = returnInteger     'Use the value entered

    End If

    ' Display the result

    MsgBox returnString, , "InitializeUserInput Example"

End Sub

 

發佈了4 篇原創文章 · 獲贊 20 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章