Here’s a quick piece of code to finish up the week to complement what we saw earlier. The idea is that on localized AutoCAD versions this code will allow the user to enter English commands without needing the underscore prefix. The code works by detecting an “unknown” command and then attempting to execute it again after prefixing an underscore to launch a global command. Which may or may not work, of course, so we certainly need to set a flag to avoid descending into an infinite loop of commands being called while prefixed by an ever-expanding legion of underscores.
Aside from that we have some code disabling auto-correct and auto-complete, as these certainly get in the way of the code working properly. These aren’t strictly system variables, so I haven’t jumped through the hoops to make sure they get set back properly afterwards. So be aware these capabilities are likely to be disabled – and then require manual re-enabling – once you’ve run this code.
Here’s the C# code in question:
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.Runtime;
namespace CommandHelper
{
public class Commands
{
// Mutex to stop unknown command handler re-entrancy
private bool _launched = false;
[CommandMethod("CMDS")]
public void CommandTranslation()
{
var doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null)
return;
// AutoComplete and AutoCorrect cause problems with
// this, so let's turn them off (we may want to warn
// the user or reset the values, afterwards)
doc.Editor.Command(
"_.-INPUTSEARCHOPTIONS",
"_autoComplete", "_No",
"_autocoRrect", "_No",
""
);
// Add our command prefixing event handler
doc.UnknownCommand += OnUnknownCommand;
}
[CommandMethod("CMDSX")]
public void StopCommandTranslation()
{
var doc = Application.DocumentManager.MdiActiveDocument;
if (doc == null)
return;
// Remove our command prefixing event handler
doc.UnknownCommand -= OnUnknownCommand;
}
async void OnUnknownCommand(
object sender, UnknownCommandEventArgs e
)
{
var doc = sender as Document;
// Check to make sure we're not re-entering the handler
if (doc != null && !_launched)
{
try
{
// Set the mutex flag and call our command
_launched = true;
await doc.Editor.CommandAsync("_" + e.GlobalCommandName);
}
catch { } // Let's not be too fussy about what we catch
finally
{
// Reset our flag, now we're done
_launched = false;
}
}
}
}
}
Be warned: this code won’t do anything useful on English versions of AutoCAD, as in that context local commands also happen to be global. So a) you won’t get an unknown command event when you call a global command and b) if you do, prefixing an underscore ain’t gonna help. :-)
You’re also going to need at least AutoCAD 2015 for this code to work, as it depends on Editor.CommandAsync().
Next week I’m officially back from vacation, so you can expect my – as it turns out uninterrupted – posting schedule to return to (i.e. carry on as) normal.