You can define a custom UI element that has a Click event and an overridable OnClick() member, and implement the functionality in a reusable manner, similar to this:
public class CommandButton : Button
{
/// <summary>
/// No AutoCAD types should appear in this method
/// if it can be jitted at design-time:
/// </summary>
protected override void OnClick()
{
// Only run the Invoke() method if
// the code is running in AutoCAD:
if(!IsDesigning)
Invoke(base.OnClick);
}
// set to true if code is not running in IDE:
internal static readonly bool IsDesigning =
!Process.GetCurrentProcess().MainModule.FileName.ToUpper().StartsWith("AC");
/// <summary>
/// OK for AutoCAD types to appear here,
/// since it will never be jitted at design-time.
/// Ideally, this would live in another helper class:
/// </summary>
static void Invoke(Action action)
{
var docmgr = Application.DocumentManager;
if(docmgr.IsApplicationContext)
{
docmgr.ExecuteInCommandContextAsync(_ =>
{
action();
return Task.CompletedTask;
}, null);
}
else
{
action();
}
}
}
With the above, the event handler for the Click event will run in the document context, without having to do anything special.