Passing arguments to .NET-defined commands
Another case of planets aligning: two different people have asked me this question in two days...
It's quite common for commands to require users to provide additional input during execution. This information might be passed in via a script or a (command) from LISP, or it may simply be typed manually or pasted in by the user.
The fact is, though, that commands don't actually take arguments. It may seem like they do, but they don't. What they do is ask for user input using dialogs or the command-line.
Here are a few tips on how to support passing of information into your commands...
Define a version of your command that asks for input via the command-line
It's very easy to define beautiful UIs in .NET applications. You absolutely should do so. But it's also helpful to provide an alternative that can be called via the command-line and from scripts. I'd suggest a couple of things here for your commands:
- Define a standard version (e.g. "MYCOMMAND") and a command-line version ("-MYCOMMAND"). It's common to prefix command-line versions of commands in AutoCAD with a hyphen (see -PURGE vs. PURGE, for instance).
- An alternative is to check for the values of FILEDIA and CMDDIA system variables - see the AutoCAD documentation on these commands to understand what effect they're meant to have on commands.
When implementing a command-line version of your command, you simply use the standard user input functions (GetXXX()) available in the Autodesk.AutoCAD.EditorInput namespace. Here's some VB.NET code showing this:
Public Sub Test()
Dim ed As Editor
ed = Application.DocumentManager.MdiActiveDocument.Editor
Dim name As PromptResult = ed.GetString(vbCr + "Enter name: ")
ed.WriteMessage("You entered: " + name.StringResult)
When it's run, you get this (typed text in red):
Enter name: Hello
You entered: Hello
By the way, I tend to put a vbCr (or "\n" in ObjectARX) in front of prompts being used in GetXXX() functions, as it's also possible to terminate text input with a space in AutoCAD: this means that even is a space is entered to launch the command, the prompt string displays on a new line.
Define a LISP version of your command
The <LispFunction> attribute allows you to declare .NET functions as LISP-callable. A very good technique is to separate the guts of your command into a separate function that is then called both by your command (after it has asked the user for the necessary input) and by the LISP-registered function, which unpackages the arguments passed into it.
To understand more about how to implement LISP-callable functions in .NET, see this previous post.