Provides experimental access to .NET assemblies through ordinary script property, method, call and index syntax.
This class is exported by the KS module.
Note: This class is experimental: it and its nested types may change or be removed without deprecation. See #Warn Experimental. Basic values and function objects are marshalled, but complex .NET types might not convert correctly.
Root := Clr.Load(AssemblyOrPath)
Loads a DLL/executable path or assembly name and returns a ManagedAssembly or ManagedNamespace wrapper. To use a library from a package feed, see #Package.
Package := Clr.LoadPackage(Provider:Name , Version, Optional)
Makes a package's assemblies available at run time, and returns a ManagedAssembly over that package's own assemblies. Its types are then reachable both from the return value and through Clr by namespace. Name takes the same Provider:PackageId form as #Package.
Version takes the same forms as the #Package directive. If Optional is true, a package or separately installed provider that cannot be made available returns an empty string instead of raising an error. Malformed package or version syntax remains an error when the provider is installed.
Note: Prefer #Package where it fits. A new request resolves every package requested so far, including those named by #Package; repeating an already loaded request with the same version, or with no version, reuses its assemblies, but an assembly which is already loaded cannot be unloaded, so a version conflict is reported rather than repaired. Use this function for a package chosen by a computed name, or one needed only on some code paths.
Note: This function needs its provider at run time. An executable built with --compile includes the provider when the compiler can tell from the call which one is used; a non-default provider named only inside a computed name must be installed beside the executable.
Invalid generic signatures raise a ValueError.
A For loop can enumerate a wrapped .NET collection, including one whose enumerator implements IEnumerator explicitly. The enumerator is disposed when enumeration ends.
A .NET enum value is passed as an Integer:
#Import "Ks" { Clr }
System := Clr.Load("System")
System.IO.File.SetUnixFileMode(Path, 0o600)
The value does not have to be a declared member, so a flag combination can be built in script with |. The member itself works equally well when read through a ManagedType, as in System.StringComparison.OrdinalIgnoreCase.
An enum returned from .NET arrives as a wrapper; use ToString for the member name. A non-numeric value passed as an enum raises a TypeError.
A Buffer or any object exposing numeric Ptr and Size properties passed where .NET expects a byte[] parameter, property or field arrives as a copy of its bytes:
#Import "Ks" { Clr }
System := Clr.Load("System")
Buf := Buffer(3)
NumPut("UChar", 72, "UChar", 105, "UChar", 33, Buf)
MsgBox System.Convert.ToBase64String(Buf) ; SGkh
Span<byte> and ReadOnlySpan<byte> parameters view the original storage for the duration of the call, so a mutable span can write into it directly. A byte[] overload is preferred when both forms fit.
Subscription := Instance.OnEvent(EventName, Callback) Subscription := Type.OnEvent(EventName, Callback) Hooks := Clr.Hooks
Subscribes Callback to a .NET event of a ManagedInstance, or to a static event of a ManagedType such as Microsoft.Win32.SystemEvents, and returns a running Clr.EventSubscription. Callback is a function object which receives the event's own arguments, typically (Sender, EventArgs). OnEvent takes precedence over a member of that name which the .NET type declares itself.
OnEvent takes exactly two arguments; any other number raises a ValueError. Calling an event's compiler-generated add_EventName or remove_EventName accessor raises a MethodError naming OnEvent. An EventName the target does not declare raises a ValueError.
An event raised on the thread which subscribed runs the callback at once, and only then can the callback's return value or error reach the .NET code which raised it. An event raised on any other thread is queued and runs in its own thread on the one which subscribed.
The subscription is an EventHook, with these members of its own:
| Member | Description |
|---|---|
EventName | The name of the event it is attached to. |
Target | The ManagedInstance or ManagedType it is attached to. |
Start() after Stop() attaches a new handler, which may run in a different position among the event's other handlers. Stopping, lifetime and Clr.Hooks work as described under EventHook.
A subscription does not keep the script running, so a script which only waits for .NET events calls Persistent.
#CSharp
public class Raiser
{
public event System.EventHandler Fired;
public void Raise() => Fired?.Invoke(this, System.EventArgs.Empty);
}
public static Raiser MakeRaiser() => new Raiser();
#EndCSharp
R := MakeRaiser()
Sub := R.OnEvent("Fired", (Sender, Args) => MsgBox("Fired"))
R.Raise() ; raised on the script's own thread, so the callback runs at once
Sub.Stop()
R.Raise() ; the subscription has ended, so nothing is shown
Name := Clr.GetNamespaceName(ManagedNamespace) Name := Clr.GetTypeName(ManagedType)
Returns the underlying full namespace or type name.
Wrapped := Clr.Wrap(Value)
Returns any value as an ordinary Clr object, with the member-access semantics described above, so the value's own full CLR surface is reachable late-bound. Map and Array are themselves CLR objects — a Map is a CLR IDictionary<object, object> and an Array an IList, so a CLR API declaring one accepts them directly — and wrapping one reaches those members from script.
The result is always a view over Value itself. To reach the .NET object a built-in is a facade over — the toolkit window behind a Gui, the HttpClient behind an Http session — call that type's own ToClr().
Wrapping something which is already a Clr object is the identity. Wrapping a ComObject yields a view over its wrapper object, not the COM interface.
The last line of this example works only on Windows.
#Import "Ks" { Clr }
arr := [1, 2, 3]
MsgBox Clr.Wrap(arr).Count ; the CLR IList surface of the Array itself
MyGui := Gui(, "Demo")
MsgBox MyGui.ToClr().Text ; Windows: the title of the toolkit window the Gui is a facade over
Inline C# (#CSharp) holding a ManagedInstance reads the raw wrapped object from its Native property. Script member access on a wrapper always dispatches to the wrapped object, so Native is unreachable from script.
A managed library can call Keysharp.Runtime.Script.TheScript.RegisterKeyStateProvider(Provider) to supply keyboard and mouse-button state to GetKeyState and KeyWait. This is a .NET host API.
The provider implements Keysharp.Components.Input.IKeyStateProvider, supplied by Keysharp.Components.Input.dll. Its method is bool TryGetKeyState(uint VirtualKey, string Mode, out bool State). VirtualKey includes mouse-button codes; Mode is L, P or T. Return true to supply State, or false to request the native query and its capability requirements. Unexpected managed exceptions raise an OSError. Queries can arrive concurrently.
Use #Startup to register the provider before capability checks and hotkey setup. Registration affects subsequent queries; earlier queries, including class static initialization, can use native state. Input capture requires a separate hook provider. Sending and controller queries use native services.
Only one provider can be registered at a time. The method rejects a null provider or a disposed script. Successful registration transfers ownership to the script and returns a System.IDisposable handle. Disposing the handle restores native queries and permits a fresh registration; repeated disposal is harmless. Otherwise the provider remains registered until script shutdown.
A provider may implement System.IDisposable. Removal or shutdown disposes it after its active queries return, possibly on the last query's thread. Supply a fresh instance for each registration, and do not dispose a registered provider yourself. A rejected registration leaves ownership with the caller.
Load the library with Clr.Load or #Package. Its installation method can reference Keysharp.Core.dll and Keysharp.Components.Input.dll, or use a #CSharp adapter to call the host API. Deploy the library and its dependencies according to its loading requirements, normally beside the application, script or .cks. The library's operating-system and driver requirements still apply; macOS execution and hardware delivery are unverified.
Note: Third-party driver and hardware capture on macOS remain unverified.
A managed library can call Keysharp.Runtime.Script.TheScript.RegisterHookProvider(Provider) with a Keysharp.Components.Input.IHookProvider once per script, on its startup thread before hooks or hotkeys are installed. Use #Startup to call the library's installation method. Registration transfers ownership on success and returns a System.IDisposable handle; disposing it restores native capture. A rejected registration leaves ownership with the caller.
Reported events enter the normal hotkey, hotstring and InputHook processing. On Windows, the provider reports physical input and native hooks continue observing injected events. On Linux and macOS, native capture is not started: the provider supplies its observed stream and marks injected events with the corresponding LLKHF/LLMHF flag. Send, Click and MouseMove keep their native senders and permission requirements; registering capture does not register a sender provider or key-state provider.
The interface declares bool SetHooks(bool Keyboard, bool Mouse, IHookHost Host, out string Message) and void CallNextHook(), and inherits System.IDisposable. SetHooks selects capture; returning false preserves the previous selection and supplies an error message. The host's KeyboardEvent and MouseEvent methods return true to suppress an event. Messages, virtual keys and flags use Windows values; scan codes use set-1 on Windows, evdev on Linux and kVK on macOS. See the interface's XML comments for the remaining field and forwarding rules.
Serialize the host's event and reset calls, and report only input from the script's session and desktop. CallNextHook must forward the current event promptly without waiting for the receiver, and SetHooks must not wait for a host callback. Report lost capture through IHookHost.CaptureLost, which stops interception and schedules an error. Call IHookHost.ResetState() before resuming input after a capture gap or session switch. Removal and shutdown dispose the provider after active host calls finish.
Installing provider hooks or blocking their mouse movement uses the provider's access mechanism and does not request native capture permissions. Other native operations retain their capability requirements.
A provider can also implement IInputDeviceProvider, with InputDeviceInfo[] GetDevices() and bool TryGetDeviceInfo(long DeviceId, string Kind, out InputDeviceInfo Device). The descriptors supply Id, Kind, Name, VendorId, ProductId and HardwareId for Input.Devices and A_EventInfo.Device. IDs belong to the provider. Without this interface, Input.Devices retains the native inventory; with it, even an empty inventory replaces native devices. Physical state is tracked from reported events; a detected HardwareId change clears it until another transition arrives.
Deploy the provider DLL, dependencies and any required driver as described by the library. Loading a library does not install a driver. The Interception package requires Windows x64 and its kernel driver.
Note: Sender providers on Linux and macOS, and third-party driver and hardware delivery, remain unverified.
A managed library can call Keysharp.Runtime.Script.TheScript.RegisterSenderProvider(Provider) with a Keysharp.Components.Input.ISenderProvider to carry SendPlay mode, including the Play mode of Click and MouseMove. Use #Startup to call the library's installation method. Event and Input sending are unaffected.
The interface declares void KeybdEvent(ushort VirtualKey, ushort ScanCode, uint Flags, ulong ExtraInfo) and void MouseEvent(uint Flags, int X, int Y, uint MouseData, ulong ExtraInfo), and inherits System.IDisposable. Each Play send reaches the provider as the events Input mode would send, using the fields of Windows' KEYBDINPUT and MOUSEINPUT, with the Play delays of SetKeyDelay and SetMouseDelay between them. Scan codes use set-1 on Windows, evdev on Linux and kVK on macOS, as for a hook provider. When SetStoreCapsLockMode turns CapsLock off for a send, the provider carries those toggles too, at the start and end of the send. Submit each event before returning and throw on failure. A call can arrive while one of the provider's own capture callbacks is waiting for the script, so do not wait for that callback.
For MouseEvent, interpret X and Y only when MOUSEEVENTF_MOVE is set. With MOUSEEVENTF_ABSOLUTE, they are normalized coordinates from 0 to 65535 spanning the virtual desktop, with MOUSEEVENTF_VIRTUALDESK set. Without MOUSEEVENTF_ABSOLUTE, they are signed relative input counts. A relative cursor move, including MouseMove(..., "R"), goes by pixels: it arrives as an absolute move to the cursor position plus the offset, or within one send, to the position the send has already moved to plus the offset. MouseMove Delta mode instead preserves X and Y as relative input counts with MOUSEEVENTF_MOVE and no MOUSEEVENTF_ABSOLUTE flag. Ignore X and Y for button and wheel events without MOUSEEVENTF_MOVE.
The script's hooks recognize its own output by ExtraInfo, so deliver it with each event. On Windows the marker counts only once the script has registered a sender provider, since other drivers can leave any value there. Where the transport cannot carry it, such as a Linux uinput device, a hook provider has to report it.
A send through a provider returns once the provider has accepted its events, which the operating system may not have processed yet. State read straight afterwards can therefore lag: GetKeyState, KeyWait and MouseGetPos can report the state from before the send, and an immediately following send can miss a modifier the previous one holds down, then release it, or start a relative move from where the cursor was before the previous move. Where a script depends on that state, Sleep briefly after the send.
A send containing Unicode text or a key without a scan code goes to the native Input path as built, before any event reaches the provider, even where Input would otherwise fall back to Event. A provider exception stops the send, which then tries to release the keys and buttons it pressed and to turn CapsLock back on if it had turned it off; those calls can fail too. Modifiers the send planned to hold but never submitted are not kept. Only then does it raise a continuable OSError.
Only one provider can be registered at a time, under the same ownership rules as a key-state provider: the returned handle restores native Play when disposed, and removal or shutdown disposes the provider after active sends finish.
#Import "Ks" { Clr }
System := Clr.Load("System")
Linq := System.Linq.Enumerable
Odds := Linq.Where([1, 2, 3, 4], n => Mod(n, 2))