-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommandExtensionExamples.cs
263 lines (238 loc) · 9.51 KB
/
CommandExtensionExamples.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/// CommandExtensionExamples.cs ActivistInvestor / Tony T.
///
/// Example code for using the types in CommandExtensions.cs
///
/// Distributed under the terms of the MIT license.
///
/// Source location:
///
/// https://github.com/ActivistInvestor/AcMgdUtility/blob/main/CommandExtensionExamples.cs
///
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices.EditorExtensions;
using Autodesk.AutoCAD.ApplicationServices.EditorInputExtensions;
namespace CommandExtensionExamples
{
public static class CommandExtensionExamples
{
/// <summary>
/// Issues the HATCHGENERATEBOUNDARY command and collects
/// all of the objects created by it and sets them to the
/// pickfirst selection set. This example will collect all
/// boundary objects generated by the command and select
/// them.
///
/// Note that this example uses extension methods for the
/// Editor class that are included below.
/// </summary>
[CommandMethod("SELECTHATCHBOUNDARY", CommandFlags.Redraw)]
public static void MyCommand()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
var per = ed.GetEntity<Hatch>("\nSelect Hatch: ");
if(per.Status != PromptStatus.OK)
return;
ObjectId hatchId = per.ObjectId;
var newIds = new ObjectIdCollection();
ed.Command<Entity>(newIds, "HATCHGENERATEBOUNDARY", hatchId, "");
if(newIds.Count > 0)
{
ed.SetImpliedSelection(newIds.ToArray());
}
else
{
ed.WriteMessage("\nFailed to capture hatch boundary object(s).");
}
}
}
}
namespace Autodesk.AutoCAD.ApplicationServices.EditorInputExtensions
{
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
public static partial class EditorInputExtensions
{
/// <summary>
/// An extended overload of the Editor's GetEntity() method
/// that uses a generic argument to constrain the selected
/// entity to instances of a type (and/or a derived type if
/// the exact argument is false), that also accepts a caller-
/// supplied function that will be called to further validate
/// a successful selection.
///
/// The validate function overcomes a problem associated with
/// repeatedly re-issing an input prompt when the method is
/// used from a modal dialog box. Without using this method,
/// repeated calls to GetEntity() from a modal dialog will
/// cause the dialog to repeatedly disappear and reappear on
/// each input prompt. This method allows validation of the
/// selected entity from a modal dialog without causing the
/// dialog to repeatedly show/hide. To accomplish this, the
/// validation method can be supplied to fully-validate the
/// user's response, and if necessary, retry input on failed
/// validation any number of times, while the dialog remains
/// hidden. When using a validation function, the function
/// can display a failure message and return false, and the
/// input prompt will be re-issued until the user cancels,
/// or the validation function returns true. A modal dialog
/// will reappear after the call to this method returns.
///
/// An example that requires a user to select a closed,
/// planar curve:
///
/// <code>
///
/// public static ObjectId GetBoundary()
/// {
/// Document doc = Application.DocumentManager.MdiActiveDocument;
/// Editor ed = doc.Editor;
/// var rslt = ed.GetEntity<Curve>("\nSelect boundary: ", false, validate);
/// if(rslt.Status == PromptStatus.Ok)
/// return result.ObjectId;
/// else
/// return ObjectId.Null;
///
/// // The validation method is called by GetEntity<T>,
/// // when an object is selected, and is passed the open
/// // entity. If the validation method returns false, the
/// // input prompt is re-issued:
///
/// bool validate(Curve crv, PromptEntityResult rslt, Editor ed)
/// {
/// if(!(curve.Closed && curve.IsPlanar))
/// {
/// ed.WriteMessage("\nInvalid selection," +
/// " requires a closed, planar curve,");
/// return false;
/// }
/// return true;
/// }
/// }
///
///
///
/// </code>
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="editor"></param>
/// <param name="message"></param>
/// <param name="validate"></param>
/// <returns></returns>
public static PromptEntityResult GetEntity<T>(this Editor editor, string message,
bool exact = false, Func<T, PromptEntityResult, Editor, bool> validate = null)
where T : Entity
{
return GetEntity<T>(editor, new PromptEntityOptions(message), exact, validate);
}
public static PromptEntityResult GetEntity<T>(this Editor editor,
PromptEntityOptions peo,
bool exact = false,
Func<T, PromptEntityResult, Editor, bool> validate = null) where T : Entity
{
if(editor == null)
throw new ArgumentNullException(nameof(editor));
if(peo == null)
throw new ArgumentNullException(nameof(peo));
if(string.IsNullOrEmpty(GetRejectMessage(peo)))
peo.SetRejectMessage($"\nInvalid selection, requires {typeof(T).Name},");
peo.AddAllowedClass(typeof(T), exact && !typeof(T).IsAbstract);
if(validate == null)
return editor.GetEntity(peo);
using(UserInteractionThunk.Begin())
{
while(true)
{
var result = editor.GetEntity(peo);
if(result.Status != PromptStatus.OK)
return result;
using(var tr = new OpenCloseTransaction())
{
T entity = tr.GetObject(result.ObjectId, OpenMode.ForRead) as T;
if(validate(entity, result, editor))
return result;
}
}
}
}
static FieldInfo rejectMessageField = typeof(PromptEntityOptions)
.GetField("m_rejectMessage", BindingFlags.Instance | BindingFlags.NonPublic);
static string GetRejectMessage(PromptEntityOptions peo)
{
return rejectMessageField.GetValue(peo) as string;
}
/// <summary>
/// Wraps EditorUserInteraction and does nothing if
/// there is no active modal window.
/// </summary>
class UserInteractionThunk : IDisposable
{
EditorUserInteraction wrapped;
public UserInteractionThunk()
{
IntPtr hwndActive = GetActiveModalWindow();
if(hwndActive != IntPtr.Zero)
{
wrapped = Start(hwndActive);
}
}
public static IDisposable Begin()
{
return new UserInteractionThunk();
}
public void Dispose()
{
if(wrapped != null)
{
wrapped.Dispose();
wrapped = null;
}
}
static EditorUserInteraction Start(IntPtr hWnd)
{
if(ctor == null)
throw new ArgumentNullException("EditorUserInteraction(IntPtr) constructor not found");
return (EditorUserInteraction)ctor.Invoke(new object[] { hWnd });
}
static ConstructorInfo ctor =
typeof(EditorUserInteraction).GetConstructor(typeof(IntPtr));
const uint GW_OWNER = 4;
[DllImport("user32.dll")]
private static extern IntPtr GetActiveWindow();
[DllImport("user32.dll")]
private static extern IntPtr GetWindow(IntPtr hWnd, uint uCmd);
[DllImport("user32.dll")]
private static extern bool IsWindowEnabled(IntPtr hWnd);
/// <summary>
/// I've come across various approaches to this problem,
/// and none (including this one) are completely foolproof.
/// </summary>
/// <returns>The handle of an active modal window, or
/// IntPtr.Zero if no active modal window is found.</returns>
static IntPtr GetActiveModalWindow()
{
IntPtr hwnd = GetActiveWindow();
if(hwnd != IntPtr.Zero && hwnd != Application.MainWindow.Handle)
{
IntPtr hwndOwner = GetWindow(hwnd, GW_OWNER);
if(hwndOwner != IntPtr.Zero && !IsWindowEnabled(hwndOwner))
return hwnd;
}
return IntPtr.Zero;
}
}
}
public static partial class TypeExtensions
{
public static ConstructorInfo GetConstructor(this Type type, params Type[] argTypes)
{
return type?.GetConstructor(BindingFlags.NonPublic | BindingFlags.Public,
null, argTypes, null);
}
}
}