明经CAD社区

 找回密码
 注册

QQ登录

只需一步,快速开始

搜索
查看: 14522|回复: 17

[Kean专集] Kean专题(5)—Commands

   关闭 [复制链接]
发表于 2009-5-19 14:17 | 显示全部楼层 |阅读模式
本帖最后由 作者 于 2009-5-19 15:02:55 编辑

原帖:http://through-the-interface.typepad.com/through_the_interface/commands/
一、AutoCAD的命令编程技术
August 11, 2006
Techniques for calling AutoCAD commands programmatically
It's quite common to want to call commands from one or other of AutoCAD's programming environments. While it's cleanest (from a purist's perspective) to use an API to perform the task you want, the quickest way - and the one which will appeal to the pragmatists (and the lazy) among us is often to call a sequence of commands. And there are, of course, a few places in AutoCAD where APIs have not been exposed, so scripting commands is the only way to achieve what you want.
Let's take the simple example of adding a line. Here's what you'd do from the different environments from a low-level API perspective:
LISP - create an association list representing the entity and then (entmake) it
VBA (or COM) - get the ModelSpace object from the active drawing and call AddLine (the COM API is probably the simplest in that respect)
.NET and ObjectARX - open the block table and then the model-space block table record, create a new line object and append it to the model-space (and to the transaction, if you're using them), closing the various objects along the way
Having first started coding for AutoCAD with LISP (for R10), I know that the simplest way to do what you want from that environment is to call the LINE command, passing in the start and end points:
(command "_LINE" "0,0,0" "100,100,0" "")
LISP is great in that respect: as you're not able to define native commands (only LISP) functions, it's perfectly acceptable to use it to script commands to do what you want, rather than rely on low-level APIs.
ObjectARX in particular has potential issues with respect to defining native commands calling commands, as AutoCAD is only "re-entrant" up to 4 levels. Without going into specifics, it's basically best to avoid calling commands using acedCommand() from ObjectARX, unless the command is registered as a LISP function using acedDefun().
While you do have to be careful when calling commands from VBA or ObjectARX, there are a few options available to you.
ObjectARX
ads_queueexpr()
This old favourite is intended to be used from acrxEntryPoint() to execute a sequence of commands after (s::startup) has been called from LISP (as you are not able to use acedCommand() from this context)
You need to declare it yourself (extern "C" void ads_queueexpr( ACHAR *);) before use
It has been unsupported as long as I can remember, but is widely-used and mentioned in the Tips & Techniques section of the ObjectARX Developer's Guide
AcApDocManager::sendStringToExecute()
This function has the advantage of a few more options being available as arguments, mainly around where to execute the string (which document, and whether it be activated), and whether to echo the string to the command-line
::SendMessage()
This is a standard Win32 platform API and so can, in effect, be used to drive AutoCAD from an external client. It uses a structure to pass the string that is often a bit tricky to set up (it became a migration issue when we switched to Unicode, for example)
IAcadDocument::SendCommand()
This COM method is the only way (other than acedCommand() or acedCmd()) to execute a command synchronously from AutoCAD (and even then it may not be completely synchronous if requiring user input)
acedCommand()
This is the ObjectARX equivalent to (command), and is genuinely synchronous. Unfortunately (as mentioned earlier) there are issues with using it directly from a natively-registered command, so I'd recommend only using it from acedDefun()-registered commands (see the ObjectARX documentation and the below sample for more details)
VBA (some of which also applies to VB)
ThisDrawing.SendCommand
This is the same as IAcadDocument::SendCommand() from C++
SendKeys
This is just a simple technique to send key-strokes to the command-line
SendMessage
This is just the Win32 API mentioned above, but declared and called from VB(A)
So, now for some sample code...


ObjectARX sample code
The first can be dropped into an ObjectARX Wizard-defined project (I used Visual Studio 2005 and ObjectARX 2007). You'll need to make sure "COM-client" is selected and you name your project "SendingCommands" (or you search and replace to change the name in the below code to something you prefer).
The code creates points along a line (from 0,0 to 5,5), using different techniques to send the command to AutoCAD. I would, of course, use the proper ObjectARX APIs to do this (creating an AcDbPoint etc.) - I just used this as an example of a command that could be sent.
It creates the first point on load, using ads_queueexpr(), and defines commands (TEST1, TEST2, TEST3 and TEST4) for the subsequent tests (the last being an acedDefun()-registered command).
  1. #include "StdAfx.h"
  2. #include "resource.h"
  3. #define szRDS _RXST("Adsk")
  4. extern "C" void ads_queueexpr( ACHAR *);
  5. //----- ObjectARX EntryPoint
  6. class CSendingCommandsApp : public AcRxArxApp {
  7. public:
  8.   CSendingCommandsApp () : AcRxArxApp () {}
  9.   virtual AcRx::AppRetCode On_kInitAppMsg (void *pkt) {
  10.     // You *must* call On_kInitAppMsg here
  11.     AcRx::AppRetCode retCode =AcRxArxApp::On_kInitAppMsg (pkt) ;
  12.     return (retCode) ;
  13.   }
  14.   virtual AcRx::AppRetCode On_kUnloadAppMsg (void *pkt) {
  15.     // You *must* call On_kUnloadAppMsg here
  16.     AcRx::AppRetCode retCode =AcRxArxApp::On_kUnloadAppMsg (pkt) ;
  17.     return (retCode) ;
  18.   }
  19.   virtual AcRx::AppRetCode On_kLoadDwgMsg(void * pkt) {
  20.     AcRx::AppRetCode retCode =AcRxArxApp::On_kLoadDwgMsg (pkt) ;
  21.     ads_queueexpr( _T("(command"_POINT" "1,1,0")") );
  22.     return (retCode) ;
  23.   }
  24.   virtual void RegisterServerComponents () {
  25.   }
  26. public:
  27.   // - AdskSendingCommands._SendStringToExecTest command (do not rename)
  28.   static void AdskSendingCommands_SendStringToExecTest(void)
  29.   {
  30.     acDocManager->sendStringToExecute(curDoc(), _T("_POINT 2,2,0 "));   
  31.   }
  32.   static void SendCmdToAcad(ACHAR *cmd)
  33.   {
  34.     COPYDATASTRUCT cmdMsg;
  35.     cmdMsg.dwData = (DWORD)1;
  36.     cmdMsg.cbData = (DWORD)(_tcslen(cmd) + 1) * sizeof(ACHAR);
  37.     cmdMsg.lpData = cmd;
  38.     SendMessage(adsw_acadMainWnd(), WM_COPYDATA, NULL, (LPARAM)&cmdMsg);
  39.   }
  40.   // - AdskSendingCommands._SendMessageTest command (do not rename)
  41.   static void AdskSendingCommands_SendMessageTest(void)
  42.   {
  43.     SendCmdToAcad(_T("_POINT 3,3,0 "));
  44.   }
  45.   // - AdskSendingCommands._SendCommandTest command (do not rename)
  46.   static void AdskSendingCommands_SendCommandTest(void)
  47.   {
  48.     try {
  49.       IAcadApplicationPtr pApp = acedGetIDispatch(TRUE);
  50.       IAcadDocumentPtr pDoc;
  51.       pApp->get_ActiveDocument(&pDoc);
  52.       pDoc->SendCommand( _T("_POINT 4,4,0 ") );
  53.     }
  54.     catch(_com_error& e) {
  55.       acutPrintf(_T("\nCOM error: %s"), (ACHAR*)e.Description());
  56.     }
  57.   }
  58.   // ----- ads_test4 symbol (do not rename)
  59.   static int ads_test4(void)
  60.   {
  61.     acedCommand(RTSTR, _T("_POINT"), RTSTR,_T("5,5,0"), RTNONE);
  62.     acedRetVoid();
  63.     return (RSRSLT);
  64.   }
  65. } ;
  66. // ----------------------------------------------------------
  67. ACED_ARXCOMMAND_ENTRY_AUTO(CSendingCommandsApp, AdskSendingCommands, _SendStringToExecTest, TEST1, ACRX_CMD_TRANSPARENT, NULL)
  68. ACED_ARXCOMMAND_ENTRY_AUTO(CSendingCommandsApp, AdskSendingCommands, _SendMessageTest, TEST2, ACRX_CMD_TRANSPARENT, NULL)
  69. ACED_ARXCOMMAND_ENTRY_AUTO(CSendingCommandsApp, AdskSendingCommands, _SendCommandTest, TEST3, ACRX_CMD_TRANSPARENT, NULL)
  70. ACED_ADSCOMMAND_ENTRY_AUTO(CSendingCommandsApp, test4, true)
  71. // ----------------------------------------------------------
  72. IMPLEMENT_ARX_ENTRYPOINT(CSendingCommandsApp)
VBA sample code
This sample defines VBA macros that create points from 6,6 to 8,8, using techniques that mirror the ones shown in the ObjectARX sample.
  1. Option Explicit OnPrivate Const WM_COPYDATA = &H4A
  2. Private Type COPYDATASTRUCT
  3.     dwData As Long
  4.     cbData As Long
  5.     lpData As String
  6. End Type
  7. Private Declare Function SendMessage Lib "user32" Alias _
  8.   "SendMessageA" (ByVal hwnd As Long, ByVal wMsg As Long, ByVal _
  9.   wParam As Long, ByVal lParam As Any) As Long
  10. Public Sub SendMessageToAutoCAD(ByVal message As String)
  11.     Dim data As COPYDATASTRUCT
  12.     Dim str As String
  13.     str = StrConv(message, vbUnicode) 'converts to Unicode
  14.     data.dwData = 1
  15.     data.lpData = str
  16.     data.cbData = (Len(str) + 2)
  17.     SendMessage(ThisDrawing.Application.hwnd, WM_COPYDATA, 0, data)
  18. End Sub
  19. Public Sub Test4()
  20.     ThisDrawing.SendCommand("_point 6,6,0 ")
  21. End Sub
  22. Public Sub Test5()
  23.     SendKeys("_point 7,7,0 ")
  24. End Sub
  25. Public Sub Test6()
  26.     SendMessageToAutoCAD("_point 8,8,0 ")
  27. End Sub

 楼主| 发表于 2009-5-19 15:01 | 显示全部楼层
九、为命令添加别名
January 31, 2008
Adding aliases for custom AutoCAD commands
I had an interesting question come in by email and thought I'd share it via this post. To summarise the request, the developer needed to allow command aliasing for their custom commands inside AutoCAD. The good news is that there's a standard mechanism that works for both built-in and custom commands: acad.pgp.
acad.pgp is now found in this location on my system:
  1. C:\Documents and Settings\walmslk\Application Data\Autodesk\AutoCAD 2008\R17.1\enu\Support\acad.pgp
复制代码
We can edit this text file to add our own command aliases at the end:
  1. NL,  *NETLOAD
  2. MCC, *MYCUSTOMCOMMAND
复制代码
Here we've simply created an alias for the standard NETLOAD command (a simple enough change, but one that saves me lots of time when developing .NET modules) and for a custom command called MYCUSTOMCOMMAND. If I type NL and then MCC at the AutoCAD command-line, after saving the file and re-starting AutoCAD, I see:
  1. Command: NL
  2. NETLOAD
  3. Command: MCC
  4. Unknown command "MYCUSTOMCOMMAND".  Press F1 for help.
复制代码
Now the fact that MCC displays an error is fine - I don't actually have a module loaded that implements the MYCUSTOMCOMMAND command - but we can see that it found the alias and used it (and the MYCUSTOMCOMMAND name could also be used to demand-load an application, for instance).

回复 支持 0 反对 1

使用道具 举报

 楼主| 发表于 2009-5-19 14:22 | 显示全部楼层

二、取消一个处于激活状态的命令

August 14, 2006
Cancelling an active command in AutoCAD
Thanks to Alexander Rivilis for this topic (he submitted a comment to my previous post that got me thinking about this addendum).

When you're asking AutoCAD to execute commands by submitting them to its command-line, it helps to make sure no command is currently active. The accepted approach is to send two escape characters to the command-line... this is adopted by our menu & toolbar macros that consistently start with ^C^C in MNU and now CUI files.

Why two? The first is to cancel the "most active" command, and the second is to drop out of either the dimension mode or the outermost command, if the innermost was actually being executed transparently. Strictly speaking there are probably a few cases where you might actually need three escape characters. Type "DIM VERT 'ZOOM" into the command-line, and you'll need three escapes to get back to the "Command:" prompt, but that's fairly obscure - two is generally considered enough for most realistic situations.

So... what constitutes an  escape character? Well, luckily we no longer need to thumb back to the  ASCII table in the back of our AutoCAD R12 Programming manuals to find this out. It's ASCII code 27, which is represented as 1B in hexadecimal notation.

A common way to send the character from C++ is to send the string "\x1B" for each escape character to AutoCAD. From VB you would tend to use Chr$(27) for the same purpose.

In terms of your choice for sending the character(s) across to AutoCAD... you can generally use one of the functions suggested previously, sendStringToExecute(), SendMessage() or SendCommand(). It won't work from ads_queueexpr(), but then given its typical usage context you shouldn't need to use it for this. Also, as Alexander very rightly pointed out in his comment, you might use PostMessage() or acedPostCommand() (more on this second one later).

SendMessage() and PostMessage() are very similar - you can check this article for the differences. I tend to prefer SendMessage() for synchronous use, as it waits to have an effect before returning, but PostMessage() is still good to have around in the toolbox (it's good for firing off keystrokes into a window's message loop).

acedPostCommand() is another undocumented function, which needs declaring in your code before use:

extern Adesk::Boolean acedPostCommand(const ACHAR* );

What's particularly interesting about this function is its use of the special keyword, which should get you back to the "Command:" prompt irrespective of command nesting:

acedPostCommand(_T("CANCELCMD"));

Then, of course, you can continue to use it as shown in my previous post:

acedPostCommand(_T("_POINT 6,6,0 "));

One quick note about cancelling commands from acedCommand(). If you pass RTNONE as the only argument to acedCommand(), this will be interpreted as an escape by AutoCAD.

 楼主| 发表于 2009-5-19 14:25 | 显示全部楼层
本帖最后由 作者 于 2009-5-25 16:14:37 编辑

三、在VLisp中调用命令的例子
August 28, 2006
Calling DIMARC from Visual LISP
This is an interesting little problem that came in from Japan last week. Basically the issue is understanding how to call the DIMARC command programmatically from LISP using (command).
The DIMARC command was introduced in AutoCAD 2006 to dimension the length of arcs or polyline arc segments. What's interesting about this problem is that it highlights different aspects of entity selection in LISP.
Firstly, let's take a look at the DIMARC command (I've put the keyboard-entered text in red below):
  1. Command: DIMARC
  2. Select arc or polyline arc segment:
  3. Specify arc length dimension location, or [Mtext/Text/Angle/Partial/Leader]:
  4. Dimension text = 10.6887
The first prompt is for the arc or polyline arc segment, the second is for the dimension location (we're not going to worry about using other options).
The classic way to select an entity is to use (entsel):
  1. Command: (entsel)
  2. Select object: (<Entity name: 7ef8e050> (22.1694 32.2269 0.0))
复制代码
This returns a list containing both the entity-name and the point picked when selecting the entity. This is going to be particularly useful in this problem, as the DIMARC command needs to know where the point was picked: this is because it has to support picking of a "complex" entity, as it works not only on arcs but on arc segments of polylines. If you use the classic technique of using (car)stripping off the point, to just pass in the entity name, it fails:
  1. Command: DIMARC
  2. Select arc or polyline arc segment: (car (entsel))
  3. Select object: <Entity name: 7ef8e050>
  4. Command:
复制代码
Whereas just passing the results of (entsel) works fine:
  1. Command: DIMARC
  2. Select arc or polyline arc segment: (entsel)
  3. Select object: (<Entity name: 7ef8e050> (22.2696 32.2269 0.0))
  4. Specify arc length dimension location, or [Mtext/Text/Angle/Partial/Leader]:
  5. Dimension text = 24.3844
So it's clear we need to keep the point in there. So we know what we have to do to select arc entities - we can pass in the results of (entsel).
Polyline entities are trickier. You can pass in the entity name, with or without the point, and the command won't work:
  1. Command: DIMARC
  2. Select arc or polyline arc segment: (entsel)
  3. Select object: (<Entity name: 7ef8e058> (51.0773 29.5726 0.0))
  4. Object selected is not an arc or polyline arc segment.
  5. Select arc or polyline arc segment:
复制代码
But we can pass in the point picked by (entsel), and let the DIMARC command do the work of determining whether the segment picked was actually an arc or not:
  1. Command: DIMARC
  2. Select arc or polyline arc segment: (cadr (entsel))
  3. Select object: (52.6305 29.5726 0.0)
  4. Specify arc length dimension location, or [Mtext/Text/Angle/Partial/Leader]:
  5. Dimension text = 9.4106
So now we're ready to put it all together.
[ Note: The below example does not take into consideration the user cancelling from (getpoint) or (entsel) - that is left as an exercise for the reader. ]
  1. (defun c:myDimArc(/ en pt ed)
  2.   (setq en (entsel "\nSelect arc or polyline arc segment: ")
  3.         pt (getpoint "\nSpecify arc length dimension location: ")
  4.         ed (entget (car en))
  5.   )
  6.   ; If the object selected is a 2D polyline (old or new)
  7.   ; then pass the point instead of the entity name
  8.   (if (member (cdr (assoc 0 ed)) '("POLYLINE" "LWPOLYLINE"))
  9.     (setq en (cadr en))
  10.   )
  11.   (command "_.DIMARC" en pt)
  12.   (princ)
  13. )
This is just an example of how you need to call the DIMARC command programmatically - with this technique you clearly lose the visual feedback from the dragging of the entity during selection (what we call the "jig" in ObjectARX). And this is ultimately an unrealistic example - you're more likely to need to call DIMARC automatically for a set of entities in a drawing than just define a simple command to request user input and pass it through.
One thing this example does demonstrate is that different commands have different needs in terms of entity selection information (some just need a selection set or an entity name, some need more that than).
 楼主| 发表于 2009-5-19 14:34 | 显示全部楼层
本帖最后由 作者 于 2009-5-25 16:17:53 编辑

四、如何向.Net定义的命令传递参数
September 01, 2006
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:
  1.     <CommandMethod("TST")> _
  2.     Public Sub Test()
  3.         Dim ed As Editor
  4.         ed = Application.DocumentManager.MdiActiveDocument.Editor
  5.         Dim name As PromptResult = ed.GetString(vbCr + "Enter name: ")
  6.         ed.WriteMessage("You entered: " + name.StringResult)
  7.     End Sub
When it's run, you get this (typed text in red):
  1. Command: tst
  2. Enter name: Hello
  3. You entered: Hello
  4. Command:
复制代码
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.
July 31, 2006
Breathing fresh life into LISP applications with a modern GUI
This recent entry on Jimmy Bergmark's JTB World Blog brought to my attention the fact that ObjectDCL is about to become an Open Source project. Chad Wanless, the father of ObjectDCL, was a very active ADN member for many years, but - according to this post on the ObjectARX discussion group - is now unable to spend time working on ObjectDCL due to a severe medical condition. In case Chad is reading this... Chad - all of us here at ADN wish you a speedy recovery and all the best for your future endeavours.
Ignoring the background behind the decision to post the technology as Open Source, this is good news for developers with legacy codebases that include user interfaces implemented using DCL (Dialog Control Language).
I did want to talk a little about what other options are available to developers of LISP applications that make use of DCL today. There are a couple of approaches to calling modules implementing new user interfaces for LISP apps, whether through COM or through .NET. I'll talk about both, but I will say that .NET is the most future-proof choice at this stage.
Both techniques work on the principle that you redesign your user interface using VB6 or VB.NET/C#, and call through to these functions from LISP. Reality is often more complex - you may have more complex interactions from (for instance) particular buttons in your dialog - but these examples demonstrate what you can do to replace a fairly simple UI where you pass the initial variables into a function and receive the modified variables at the other end, once the user closes the dialog. You can also extend it to handle more complex situations, but there may be much more work needed - perhaps even use of AutoCAD's managed API from within the dialog code.
COM: Using a VB ActiveX DLL from Visual LISP
For an in-depth description of this technique, ADN members can find the information here. I apologise to those who are not able to access this content, but I don't want to dillute the issue by copying/pasting the whole article into this blog. Especially as this technique is describing the use of VB6, which is no longer at the forefront of Microsoft's development efforts.
The approach is to create an ActiveX DLL project in VB6, which is simply a COM module implementing code that can be referenced and called using a ProgID. AutoCAD's COM Automation interface exposes a method called GetInterfaceObject from the Application object that simply calls the equivalent of CreateObject on the ProgID passed in, but within AutoCAD's memory space. Once you've loaded a module using GetInterfaceObject, not only can you then call code displaying fancy VB-generated UIs from LISP, but because the code is in the same memory space as AutoCAD, it executes very quickly - on a par with VBA, ObjectARX or the managed API in terms of the speed with which it can access AutoCAD's object model.
.NET: Defining LISP-callable functions from a .NET application
The following technique is really the more future-proof approach, and has become possible since the implementation of "LISP callable wrappers" in AutoCAD 2007's managed API. Essentially it comes down to the ability to declare specific .NET functions as being LISP-callable. If you look back at one of my early posts about creating a .NET application, you'll notice the use of an attribute to declare a command, such as <CommandMethod("MyCommand")>. With AutoCAD 2007 you can simply use <LispFunction("MyLispFunction")> to denote a function that can be called directly from LISP.
From there it's simply a matter of unpackaging the arguments passed in and packaging up the results (the bit in-between is where you get to have fun, using .NET capabilities to create beautiful user interfaces or to integrate with other systems etc., etc.). Here's some code to show the handling of arguments and packaging of the results:
  1. <LispFunction("LISPfunction")> _
  2. Public Function VBfunction(ByVal rbfArgs As ResultBuffer) As ResultBuffer
  3.     'Get the arguments passed in...
  4.     Dim arInputArgs As Array
  5.     Dim realArg1 As Double
  6.     Dim intArg2 As Integer
  7.     Dim strArg3 As String
  8.     arInputArgs = rbfArgs.AsArray
  9.     realArg1 = CType(arInputArgs.GetValue(0), TypedValue).Value
  10.     intArg2 = CType(arInputArgs.GetValue(1), TypedValue).Value
  11.     strArg3 = CType(arInputArgs.GetValue(2), TypedValue).Value
  12.     'Do something interesting here...
  13.     '...
  14.     '...
  15.     'Package the results...
  16.     'Use RTREAL (5001) for doubles
  17.     'Use RTSTR (5003) for strings
  18.     'Use RTSHORT (5005) for integers
  19.     Dim rbfResult As ResultBuffer
  20.     rbfResult = New ResultBuffer( _
  21.         New TypedValue(CInt(5001), 3.14159), _
  22.         New TypedValue(CInt(5003), 42), _
  23.         New TypedValue(CInt(5005), "Goodbye!"))
  24.     Return rbfResult
  25. End Function
The code assumes the first argument passed in will be a real, followed by an integer and then finally a string. Here's what happens if you call the code like this:
  1. Command: (LISPfunction 1.234 9876 "Hello!")
  2. (3.14159 42 "Goodbye!")
复制代码
Here are a couple of useful articles on the ADN site regarding this:
LispFunction examples for AutoLISP to .NET
      
.NET ResultBuffer returns dotted pairs to Visual LISP instead of normal list
 楼主| 发表于 2009-5-19 14:43 | 显示全部楼层
五、使用委托取消命令
October 31, 2006
Blocking AutoCAD commands from .NET
Thanks to Viru Aithal from the DevTech team in India team for this idea (he reminded me of this technique in a recent ADN support request he handled).
A quick disclaimer: the technique shown in this entry could really confuse your users, if implemented with inadequate care. Please use it for good, not evil.
I talked at some length in previous posts about MDI in AutoCAD, and how various commands lock documents when they need to work on them. When commands try to lock (or unlock) a document, an event gets fired. You can respond to this event in your AutoCAD .NET module, asking AutoCAD to veto the operation requesting the lock.
For some general background on events in .NET, I’d suggest checking out this information on MSDN, both from the Developer’s Guide and from MSDN Magazine. To see how they work in AutoCAD, take a look at the EventsWatcher sample on the ObjectARX SDK, under samples/dotNet/EventsWatcher. This is a great way to see what information is provided via AutoCAD events.
It seems that almost every command causes the DocumentLockModeChanged event to be fired – I would say every command, but I can imagine there being commands that don’t trigger it, even if the technique appears to work even for commands that have no reason to lock the current document, such as HELP.
As you can imagine, having something block commands that a user expects to use could result in a serious drop in productivity, but there are genuine cases where you might have a legitimate need to disable certain product functionality, such as to drive your users through a more automated approach to performing the same task. This is not supposed to act as a fully-fledged security layer – an advanced user could easily prevent a module from being loaded, which invalidates this technique – but it could still be used to help stop the majority of users from doing something that might (for instance) break the drawing standards implemented in their department.
So, let’s take a look at what needs to happen to define and register our event handler.
Firstly, we must declare a callback function somewhere in our code that we will register as an event handler. In this case we’re going to respond to the DocumentLockModeChanged event, and so will take as one of our arguments an object of type DocumentLockModeChangedEventArgs:
VB.NET:
  1. Private Sub vetoLineCommand (ByVal sender As Object, _
  2.   ByVal e As DocumentLockModeChangedEventArgs)
  3.   If (e.GlobalCommandName = "LINE") Then
  4.     e.Veto()
  5.   End If
  6. End Sub
C#:
  1. private void vetoLineCommand(
  2.   object sender,
  3.   DocumentLockModeChangedEventArgs e)
  4. {
  5.   if (e.GlobalCommandName == "LINE")
  6.   {
  7.     e.Veto();
  8.   }
  9. }

This callback function, named vetoLineCommand(), simply checks whether the command that is requesting the change in document lock mode is the LINE command, and, if so, it then vetoes it. In our more complete sample, later on, we’ll maintain a list of commands to veto, which can be manipulated by the user using come commands we define (you will not want to do this in your application – this is for your own testing during development).
Next we need to register the command. This event belongs to the DocumentManager object, but the technique for registering events is different between VB.NET and C#. In VB.NET you use the AddHandler() keyword, referring to the DocumentLockModeChanged event from the DocumentManager object – in C# you add it directly to the DocumentLockModeChanged property. This could be done from a command or from the Initialize() function, as I’ve done in the complete sample further below.
VB.NET:
  1. Dim dm As DocumentCollection = Application.DocumentManager()
  2. AddHandler dm.DocumentLockModeChanged, AddressOf vetoLineCommand
C#:
  1. DocumentCollection dm = Application.DocumentManager;
  2. dm.DocumentLockModeChanged += new DocumentLockModeChangedEventHandler(vetoLineCommand);
复制代码
That's really all there is to it... as mentioned, the complete sample maintains a list of commands that are currently being vetoed. I've made this shared/static, and so it will be shared across documents (so if you try to modify this in concurrent drawings, you might get some interesting results).
Here's the complete sample (just to reiterate - use this technique both at your own risk and with considerable caution).
VB.NET:
  1. Imports Autodesk.AutoCAD.Runtime
  2. Imports Autodesk.AutoCAD.ApplicationServices
  3. Imports Autodesk.AutoCAD.EditorInput
  4. Imports System.Collections.Specialized
  5. Namespace VetoTest
  6.   Public Class VetoCmds
  7.     Implements IExtensionApplication
  8.     Shared cmdList As StringCollection _
  9.       = New StringCollection
  10.     Public Sub Initialize() _
  11.       Implements IExtensionApplication.Initialize
  12.       Dim dm As DocumentCollection
  13.       dm = Application.DocumentManager()
  14.       AddHandler dm.DocumentLockModeChanged, _
  15.         AddressOf vetoCommandIfInList
  16.     End Sub
  17.     Public Sub Terminate() _
  18.       Implements IExtensionApplication.Terminate
  19.       Dim dm As DocumentCollection
  20.       dm = Application.DocumentManager()
  21.       RemoveHandler dm.DocumentLockModeChanged, _
  22.         AddressOf vetoCommandIfInList
  23.     End Sub
  24.     <CommandMethod("ADDVETO")> _
  25.     Public Sub AddVeto()
  26.       Dim ed As Editor _
  27.         = Application.DocumentManager.MdiActiveDocument.Editor
  28.       Dim pr As PromptResult
  29.       pr = ed.GetString(vbLf + _
  30.         "Enter command to veto: ")
  31.       If (pr.Status = PromptStatus.OK) Then
  32.         If (cmdList.Contains(pr.StringResult.ToUpper())) Then
  33.           ed.WriteMessage(vbLf + _
  34.             "Command already in veto list.")
  35.         Else
  36.           cmdList.Add(pr.StringResult.ToUpper())
  37.           ed.WriteMessage( _
  38.             vbLf + "Command " + _
  39.             pr.StringResult.ToUpper() + _
  40.             " added to veto list.")
  41.         End If
  42.       End If
  43.     End Sub
  44.     <CommandMethod("LISTVETOES")> _
  45.     Public Sub ListVetoes()
  46.       Dim ed As Editor _
  47.         = Application.DocumentManager.MdiActiveDocument.Editor
  48.       ed.WriteMessage( _
  49.         "Commands currently on veto list: " + vbLf)
  50.       For Each str As String In cmdList
  51.         ed.WriteMessage(str + vbLf)
  52.       Next
  53.     End Sub
  54.     <CommandMethod("REMVETO")> _
  55.     Public Sub RemoveVeto()
  56.       ListVetoes()
  57.       Dim ed As Editor _
  58.         = Application.DocumentManager.MdiActiveDocument.Editor
  59.       Dim pr As PromptResult
  60.       pr = ed.GetString( _
  61.         "Enter command to remove from veto list: ")
  62.       If (pr.Status = PromptStatus.OK) Then
  63.         If (cmdList.Contains(pr.StringResult.ToUpper())) Then
  64.           cmdList.Remove(pr.StringResult.ToUpper())
  65.         Else
  66.           ed.WriteMessage(vbLf + _
  67.             "Command not found in veto list.")
  68.         End If
  69.       End If
  70.     End Sub
  71.     Private Sub vetoCommandIfInList(ByVal sender As Object, _
  72.       ByVal e As DocumentLockModeChangedEventArgs)
  73.       If (cmdList.Contains(e.GlobalCommandName.ToUpper())) Then
  74.         e.Veto()
  75.       End If
  76.     End Sub
  77.   End Class
  78. End Namespace
C#:
  1. using Autodesk.AutoCAD.EditorInput;
  2. using Autodesk.AutoCAD.ApplicationServices;
  3. using Autodesk.AutoCAD.Runtime;
  4. using System;
  5. using System.Collections.Specialized;
  6. namespace VetoTest
  7. {
  8.   public class VetoCmds : IExtensionApplication
  9.   {
  10.     static StringCollection cmdList =
  11.       new StringCollection();
  12.     public void Initialize()
  13.     {
  14.       DocumentCollection dm =
  15.         Application.DocumentManager;
  16.       dm.DocumentLockModeChanged += new
  17.         DocumentLockModeChangedEventHandler(
  18.           vetoCommandIfInList
  19.         );
  20.     }
  21.     public void Terminate()
  22.     {
  23.       DocumentCollection dm;
  24.       dm = Application.DocumentManager;
  25.       dm.DocumentLockModeChanged -= new
  26.         DocumentLockModeChangedEventHandler(
  27.           vetoCommandIfInList
  28.         );
  29.     }
  30.     [CommandMethod("ADDVETO")]
  31.     public void AddVeto()
  32.     {
  33.       Editor ed =
  34.         Application.DocumentManager.MdiActiveDocument.Editor;
  35.       PromptResult pr =
  36.         ed.GetString("\nEnter command to veto: ");
  37.       if (pr.Status == PromptStatus.OK)
  38.       {
  39.         if (cmdList.Contains(pr.StringResult.ToUpper()))
  40.         {
  41.           ed.WriteMessage(
  42.             "\nCommand already in veto list."
  43.           );
  44.         }
  45.         else
  46.         {
  47.           cmdList.Add(pr.StringResult.ToUpper());
  48.           ed.WriteMessage(
  49.             "\nCommand " +
  50.             pr.StringResult.ToUpper() +
  51.             " added to veto list.");
  52.         }
  53.       }
  54.     }
  55.     [CommandMethod("LISTVETOES")]
  56.     public void ListVetoes()
  57.     {
  58.       Editor ed =
  59.         Application.DocumentManager.MdiActiveDocument.Editor;
  60.       ed.WriteMessage("Commands currently on veto list:\n");
  61.       foreach (string str in cmdList)
  62.       {
  63.         ed.WriteMessage(str + "\n");
  64.       }
  65.     }
  66.     [CommandMethod("REMVETO")]
  67.     public void RemoveVeto()
  68.     {
  69.       ListVetoes();
  70.       Editor ed =
  71.         Application.DocumentManager.MdiActiveDocument.Editor;
  72.       PromptResult pr;
  73.       pr =
  74.         ed.GetString(
  75.           "Enter command to remove from veto list: "
  76.         );
  77.       if (pr.Status == PromptStatus.OK)
  78.       {
  79.         if (cmdList.Contains(pr.StringResult.ToUpper()))
  80.         {
  81.           cmdList.Remove(pr.StringResult.ToUpper());
  82.         }
  83.         else
  84.         {
  85.           ed.WriteMessage(
  86.             "\nCommand not found in veto list."
  87.           );
  88.         }
  89.       }
  90.     }
  91.     private void vetoCommandIfInList(
  92.       object sender,
  93.       DocumentLockModeChangedEventArgs e)
  94.     {
  95.       if (cmdList.Contains(e.GlobalCommandName.ToUpper()))
  96.       {
  97.         e.Veto();
  98.       }
  99.     }
  100.   }
  101. }
In terms of usage, it should be simple enough to work out while playing with it:
ADDVETO adds commands to the veto list
LISTVETOES lists the commands on the veto list
REMVETO removes commands from the veto list
These commands are really only intended for you to try out different commands on the veto list, to see what happens. If you need to control use of command(s) from your application, you should not allow your users to manipulate the list of blocked commands themselves.
 楼主| 发表于 2009-5-19 14:45 | 显示全部楼层
六、替换 "Open" 命令
March 04, 2007
Replacing AutoCAD's OPEN command using .NET
This very good question came in by email from Patrick Nikoletich:
I was wondering what the preferred method for overriding the default “Open” common dialog in AutoCAD 2007 would be? I can catch the event but can’t send AutoCAD a command to cancel the request so I can launch my Win Form instead.
This is quite a common requirement - especially for people integrating document management systems with AutoCAD.
The simplest way to accomplish this - and this technique goes back a bit - is to undefine the OPEN command, replacing it with your own implementation. The classic way to do this from LISP was to use the (command) function to call the UNDEFINE command on OPEN, and then use (defun) to implement your own (c:open) function.
This technique can be adapted for use with .NET. The following C# code calls the UNDEFINE command in its initialization and then implements an OPEN command of its own.
A few notes on the implementation:
I'm using the COM SendCommand(), rather than SendStringToExecute(), as it is called synchronously and is executed before the command gets defined
Unfortunately this causes the UNDEFINE command to be echoed to the command-line, an undesired side effect.
I have not tested this being loaded on AutoCAD Startup - it may require some work to get the initialization done appropriately, if this is a requirement (as SendCommand is called on the ActiveDocument).
I've implemented the OPEN command very simply - just to request a filename from the user with a standard dialog - and then call a function to open this file. More work may be needed to tailor this command's behaviour to match AutoCAD's or to match your application requirements.
This is defined as a session command, allowing it to transfer focus to the newly-opened document. It does not close the active document, which AutoCAD's OPEN command does if the document is "default" and unedited (such as "Drawing1.dwg").
And so here's the code:
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.EditorInput;
  3. using Autodesk.AutoCAD.Runtime;
  4. using Autodesk.AutoCAD.Interop;
  5. using System.Runtime.InteropServices;
  6. namespace RedefineOpen
  7. {
  8.   public class CommandRedefinitions
  9.   : Autodesk.AutoCAD.Runtime.IExtensionApplication
  10.   {
  11.     public void Initialize()
  12.     {
  13.       AcadApplication app =
  14.         (AcadApplication)Application.AcadApplication;
  15.       app.ActiveDocument.SendCommand("_.UNDEFINE _OPEN ");
  16.     }
  17.     public void Terminate(){}
  18.     [CommandMethod("OPEN", CommandFlags.Session)]
  19.     static public void Open()
  20.     {
  21.       DocumentCollection dm = Application.DocumentManager;
  22.       Editor ed = dm.MdiActiveDocument.Editor;
  23.       PromptOpenFileOptions opts =
  24.         new PromptOpenFileOptions(
  25.           "Select a drawing file (for a custom command)"
  26.         );
  27.       opts.Filter = "Drawing (*.dwg)";
  28.       PromptFileNameResult pr = ed.GetFileNameForOpen(opts);
  29.       if (pr.Status == PromptStatus.OK)
  30.       {
  31.         dm.Open(pr.StringResult);
  32.       }
  33.     }
  34.   }
  35. }
 楼主| 发表于 2009-5-19 14:48 | 显示全部楼层
七、获取 .NET-defined 的命令列表
March 15, 2007
Getting the list of .NET-defined commands in AutoCAD
Here's an interesting question that came in from Kerry Brown:
Is there a way to determine the names of Commands loaded into Acad from assemblies ... either a global list or a list associated with a specific assembly ... or both :-)
I managed to put some code together to do this (although I needed to look into how AutoCAD does it to get some of the finer points). I chose to implement two types of command - one that gets the commands for all the loaded assemblies, and one that works for just the currently-executing assembly. The first one is quite slow, though - it takes time to query every loaded assembly - so I added a command that only queries assemblies with explicit CommandClass attributes.
I didn't write a command to get the commands defined by a specified assembly - that's been left as an exercise for the reader. :-)
Here is the C# code:
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.EditorInput;
  3. using Autodesk.AutoCAD.Runtime;
  4. using System;
  5. using System.Reflection;
  6. using System.Collections.Specialized;
  7. namespace GetLoadedCommands
  8. {
  9.   public class Commands
  10.   {
  11.     [CommandMethod("TC")]
  12.     static public void ListCommandsFromThisAssembly()
  13.     {
  14.       // Just get the commands for this assembly
  15.       DocumentCollection dm =
  16.         Application.DocumentManager;
  17.       Editor ed =
  18.         dm.MdiActiveDocument.Editor;
  19.       Assembly asm =
  20.         Assembly.GetExecutingAssembly();
  21.       string[] cmds = GetCommands(asm, false);
  22.       foreach (string cmd in cmds)
  23.       {
  24.         ed.WriteMessage(cmd + "\n");
  25.       }
  26.     }
  27.     [CommandMethod("LCM")]
  28.     static public void ListMarkedCommands()
  29.     {
  30.       // Get the commands for all assemblies,
  31.       //  but only those with explicit
  32.       // CommandClass attributes (much quicker)
  33.       StringCollection cmds = new StringCollection();
  34.       DocumentCollection dm =
  35.         Application.DocumentManager;
  36.       Editor ed =
  37.         dm.MdiActiveDocument.Editor;
  38.       Assembly[] asms =
  39.         AppDomain.CurrentDomain.GetAssemblies();
  40.       foreach (Assembly asm in asms)
  41.       {
  42.         cmds.AddRange(GetCommands(asm, true));
  43.       }
  44.       foreach (string cmd in cmds)
  45.       {
  46.         ed.WriteMessage(cmd + "\n");
  47.       }
  48.     }
  49.     [CommandMethod("LC")]
  50.     static public void ListCommands()
  51.     {
  52.       // Get the commands for all assemblies,
  53.       // marked or otherwise (much slower)
  54.       StringCollection cmds = new StringCollection();
  55.       DocumentCollection dm =
  56.         Application.DocumentManager;
  57.       Editor ed =
  58.         dm.MdiActiveDocument.Editor;
  59.       Assembly[] asms =
  60.         AppDomain.CurrentDomain.GetAssemblies();
  61.       foreach (Assembly asm in asms)
  62.       {
  63.         cmds.AddRange(GetCommands(asm, false));
  64.       }
  65.       foreach (string cmd in cmds)
  66.       {
  67.         ed.WriteMessage(cmd + "\n");
  68.       }
  69.     }
  70.     private static string[] GetCommands(
  71.       Assembly asm,
  72.       bool markedOnly
  73.     )
  74.     {
  75.       StringCollection sc = new StringCollection();
  76.       object[] objs =
  77.         asm.GetCustomAttributes(
  78.           typeof(CommandClassAttribute),
  79.           true
  80.         );
  81.       Type[] tps;
  82.       int numTypes = objs.Length;
  83.       if (numTypes > 0)
  84.       {
  85.         tps = new Type[numTypes];
  86.         for(int i=0; i < numTypes; i++)
  87.         {
  88.           CommandClassAttribute cca =
  89.             objs[i] as CommandClassAttribute;
  90.           if (cca != null)
  91.           {
  92.             tps[i] = cca.Type;
  93.           }
  94.         }
  95.       }
  96.       else
  97.       {
  98.         // If we're only looking for specifically
  99.         // marked CommandClasses, then use an
  100.         // empty list
  101.         if (markedOnly)
  102.           tps = new Type[0];
  103.         else
  104.           tps = asm.GetExportedTypes();
  105.       }
  106.       foreach (Type tp in tps)
  107.       {
  108.         MethodInfo[] meths = tp.GetMethods();
  109.         foreach (MethodInfo meth in meths)
  110.         {
  111.           objs =
  112.             meth.GetCustomAttributes(
  113.               typeof(CommandMethodAttribute),
  114.               true
  115.             );
  116.           foreach (object obj in objs)
  117.           {
  118.             CommandMethodAttribute attb =
  119.               (CommandMethodAttribute)obj;
  120.             sc.Add(attb.GlobalName);
  121.           }
  122.         }
  123.       }
  124.       string[] ret = new string[sc.Count];
  125.       sc.CopyTo(ret,0);
  126.       return ret;
  127.     }
  128.   }
  129. }
And here's what happens when you run the various commands:
  1. Command: TC
  2. TC
  3. LCM
  4. LC
  5. Command: LC
  6. layer
  7. TC
  8. LCM
  9. LC
  10. Command: LCM
  11. layer
复制代码
Note: you'll see that our own module's command are not listed by LCM... if you add the CommandClass attribute, as mentioned in this earlier post, then they will be:
  1. [assembly:
  2.   CommandClass(
  3.     typeof(GetLoadedCommands.Commands)
  4.   )
  5. ]
复制代码
 楼主| 发表于 2009-5-19 14:52 | 显示全部楼层

八、

August 17, 2007
CommandComplete bonus tool
Most members of my team (DevTech) have a background in software development, having developed code professionally in previous jobs. People often join DevTech because they enjoy the variety and flexibility the role brings as well as the direct communication we have with the Autodesk development community.

That said, we still like to hone our coding skills - some of this we get from fielding questions we receive from ADN members but it's also helpful to work on the odd software project. Back in the day - during my stint living in India - DevTech was part of Autodesk Consulting and so members of the team were often involved in developing code for customers. These days our mandate is clearer, to focus on providing services through the Autodesk Developer Network.

The majority of the software projects we currently work on are samples for publication, whether as DevNotes on the ADN site or as samples we ship with the ObjectARX SDK. During the last year or so we've been running an internal initiative called "DevTech Labs", through which we develop customer-oriented features and bonus tools for posting to Autodesk Labs.

The first fruit of these labours is now available: the CommandComplete bonus tool. Sreekar Devatha, a member of the DevTech team based in India, was the primary developer on this project. I think he's done a great job on this very useful tool. :-)

This post from Scott Sheppard lists some of the feedback we've received to date. There's also further feedback received by email and the discussion group that we'll take into account when working on an update to this tool.

 楼主| 发表于 2009-5-19 17:41 | 显示全部楼层
十、在.Net中使用P/Invoke调用ObjectArx
August 04, 2008
Using the P/Invoke Interop Assistant to help call ObjectARX from .NET
Thanks to Gopinath Taget, from DevTech Americas, for letting me know of this tool's existence.
I've often battled to create Platform Invoke signatures for unmanaged C(++) APIs in .NET applications, and it seems this tool is likely to save me some future pain. The tool was introduced in an edition of MSDN Magazine, earlier this year.
[For those unfamiliar with P/Invoke, I recommend this previous post.]
While the Interop Assistant can be used for creating function signatures to call into .NET assemblies from unmanaged applications, I'm usually more interested in the reverse: calling unmanaged functions from .NET.
Let's take a quick spin with the tool, working with some functions from the ObjectARX includes folder...
A great place to start is the aced.h file, as it contains quite a few C-standard functions that are callable via P/Invoke.
After installing and launching the tool, the third tab can be used for generation of C# (DllImport) or VB.NET (Declare) signatures for unmanaged function(s). To get started we'll go with an easy one:
  1. void acedPostCommandPrompt();
复制代码
After posting the code into the "Native Code Snippet" window, we can generate the results for C#:

And for VB.NET:

Taking a quick look at the generated signature (I'll choose the C# one, as usual), we can see it's slightly incomplete:
  1. public partial class NativeMethods
  2. {
  3.   /// Return Type: void
  4.   [System.Runtime.InteropServices.DllImportAttribute(
  5.     "<Unknown>",
  6.     EntryPoint = "acedPostCommandPrompt")]
  7.   public static extern void acedPostCommandPrompt();
  8. }
复制代码
We need to replace "<Unknown>" with the name of the EXE or DLL from which this function is exported: this is information that was not made available to the tool, as we simply copy & pasted a function signature from a header file. This previous post (the one that gives an introduction to P/Invoke) shows a technique for identifying the appropriate module to use.
Now let's try an altogether more complicated header:
  1. int acedCmdLookup(const ACHAR* cmdStr, int globalLookup,
  2.                   AcEdCommandStruc* retStruc,
  3.                   int skipUndef = FALSE);
复制代码
To get started, we simply paste this into the "Native Code Snippet" window, once again:

There are a few problems. Copying in the definition for ACHAR (from AdAChar.h), solves the first issue, but copying in the definition for AcEdCommandStruc (from accmd.h) identifies two further issues:

The first is easy to fix - we just copy and paste the definition of AcRxFunctionPtr from accmd.h. The second issue - defining AcEdCommand - is much more complicated, and in this case there isn't a pressing need for us to bother as the information contained in the rest of the AcEdCommandStruc structure is sufficient for this example. So we can simple set this to a void* in the structure:

OK, so we now have our valid P/Invoke signature, which we can integrate into a C# test application:
  1. using Autodesk.AutoCAD.ApplicationServices;
  2. using Autodesk.AutoCAD.DatabaseServices;
  3. using Autodesk.AutoCAD.EditorInput;
  4. using Autodesk.AutoCAD.Runtime;
  5. using System.Runtime.InteropServices;
  6. namespace PInvokeTest
  7. {
  8.   public delegate void AcRxFunctionPtr();
  9.   [StructLayoutAttribute(LayoutKind.Sequential)]
  10.   public struct AcEdCommandStruc
  11.   {
  12.     public AcRxFunctionPtr fcnAddr;
  13.     public int flags;
  14.     public System.IntPtr app;
  15.     public System.IntPtr hResHandle;
  16.     public System.IntPtr cmd;
  17.   }
  18.   [StructLayoutAttribute(LayoutKind.Sequential)]
  19.   public struct HINSTANCE__
  20.   {
  21.     public int unused;
  22.   }
  23.   public class Commands
  24.   {
  25.     [DllImportAttribute(
  26.       "acad.exe",
  27.       EntryPoint = "acedCmdLookup")
  28.     ]
  29.     public static extern int acedCmdLookup(
  30.       [InAttribute()]
  31.       [MarshalAsAttribute(UnmanagedType.LPWStr)] string cmdStr,
  32.       int globalLookup,
  33.       ref AcEdCommandStruc retStruc,
  34.       int skipUndef
  35.     );
  36.     [CommandMethod("LC")]
  37.     static public void LookupCommand()
  38.     {
  39.       Document doc =
  40.         Application.DocumentManager.MdiActiveDocument;
  41.       Database db = doc.Database;
  42.       Editor ed = doc.Editor;
  43.       PromptStringOptions pso =
  44.         new PromptStringOptions(
  45.           "\nEnter name of command to look-up: "
  46.         );
  47.       PromptResult pr = ed.GetString(pso);
  48.       if (pr.Status != PromptStatus.OK)
  49.         return;
  50.       AcEdCommandStruc cs = new AcEdCommandStruc();
  51.       int res =
  52.         acedCmdLookup(pr.StringResult, 1, ref cs, 1);
  53.       if (res == 0)
  54.         ed.WriteMessage(
  55.           "\nCould not find command definition." +
  56.           " It may not be defined in ObjectARX."
  57.         );
  58.       else
  59.       {
  60.         CommandFlags cf = (CommandFlags)cs.flags;
  61.         ed.WriteMessage(
  62.           "\nFound the definition of {0} command. " +
  63.           " It has command-flags value of "{1}".",
  64.           pr.StringResult.ToUpper(),
  65.           cf
  66.         );
  67.         PromptKeywordOptions pko =
  68.           new PromptKeywordOptions(
  69.             "\nAttempt to invoke this command?"
  70.           );
  71.         pko.AllowNone = true;
  72.         pko.Keywords.Add("Yes");
  73.         pko.Keywords.Add("No");
  74.         pko.Keywords.Default = "No";
  75.         PromptResult pkr =
  76.           ed.GetKeywords(pko);
  77.         if (pkr.Status == PromptStatus.OK)
  78.         {
  79.           if (pkr.StringResult == "Yes")
  80.           {
  81.             // Not a recommended way of invoking
  82.             // commands. Use SendCommand() or
  83.             // SendStringToExecute()
  84.             cs.fcnAddr.Invoke();
  85.           }
  86.         }
  87.       }
  88.     }
  89.   }
  90. }
Our LC command looks up a command based on its command-name and tells us the flags that were used to define it (Modal, Session, Transparent, UsePickSet, etc.). It will then offer the option to invoke it, as we have the function address as another member of the AcEdCommandStruc populated by the acedCmdLookup() function. I do not recommend using this approach for calling commands - not only are we relying on a ill-advised mechanism in ObjectARX for doing so, we're calling through to it from managed code - we're just using this as a more complicated P/Invoke example and investigating what can (in theory) be achieved with the results. If you're interested in calling commands from .NET, see this post.
By the way, if you're trying to get hold of P/Invoke signature for the Win32 API, I recommend checking here first.

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?注册

x
您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|CAD论坛|CAD教程|CAD下载|联系我们|关于明经|明经通道 ( 粤ICP备05003914号 )  
©2000-2023 明经通道 版权所有 本站代码,在未取得本站及作者授权的情况下,不得用于商业用途

GMT+8, 2024-4-24 20:22 , Processed in 1.289309 second(s), 25 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表