forked from menees/Libraries
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComObject.Core.cs
More file actions
91 lines (72 loc) · 1.86 KB
/
ComObject.Core.cs
File metadata and controls
91 lines (72 loc) · 1.86 KB
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
namespace Menees.Windows
{
#region Using Directives
using System;
using System.Dynamic;
using System.Reflection;
#endregion
// https://github.com/dotnet/runtime/issues/12587#issuecomment-534611966
// A small wrapper around COM interop to make it more easy to use.
internal class ComObject : DynamicObject
{
#region Constructors
public ComObject(object instance)
{
this.Instance = instance;
}
#endregion
#region Public Properties
public object Instance { get; }
#endregion
#region Public Methods
public static ComObject CreateObject(string progID)
{
return new ComObject(Activator.CreateInstance(Type.GetTypeFromProgID(progID, true)));
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Instance.GetType().InvokeMember(
binder.Name,
BindingFlags.GetProperty,
Type.DefaultBinder,
this.Instance,
Array.Empty<object>());
result = WrapIfRequired(result);
return true;
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
this.Instance.GetType().InvokeMember(
binder.Name,
BindingFlags.SetProperty,
Type.DefaultBinder,
this.Instance,
new object[] { value });
return true;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = this.Instance.GetType().InvokeMember(
binder.Name,
BindingFlags.InvokeMethod,
Type.DefaultBinder,
this.Instance,
args);
result = WrapIfRequired(result);
return true;
}
#endregion
#region Private Methods
// https://github.com/dotnet/runtime/issues/12587#issuecomment-578431424
private static object WrapIfRequired(object obj)
{
object result = obj;
if (obj != null && !obj.GetType().IsPrimitive)
{
result = new ComObject(obj);
}
return result;
}
#endregion
}
}