Public release

This commit is contained in:
2026-10-07 15:31:23 +00:00
commit 2c20243a75
26 changed files with 1575 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
bin/
obj/
dist/
artifacts/
*.user
+9
View File
@@ -0,0 +1,9 @@
# Changelog
## 0.1.0
- Added a Windows tray application with immediate and short-hold activation.
- Added release-to-select for recognized native and accessible context menus.
- Added deliberate-movement protection, submenu handling, cancellation, stale-target checks, and generated-input tagging.
- Added application scope, exclusions, configurable bypass, pause/resume hotkey, optional startup, and atomic local preferences.
- Added a practice area, native input integration checks, Windows icon, and README artwork.
+62
View File
@@ -0,0 +1,62 @@
# UniClik
![UniClik: Hold. Hover. Release.](assets/uniclik-readme-preview.png)
UniClik is a small Windows tray utility that opens your context menu while you hold the right mouse button. Move over an enabled command and release to choose it.
The banner illustrates the gesture. The application uses the target app's own menus, with their normal appearance and commands.
**[Download the Windows x64 preview](https://git.knickqueue.win/Knick/UniClik/releases)**, extract the ZIP into a permanent folder, and run `UniClik.exe`. Version 0.1.0 is a compatibility preview; see the [validation record](docs/validation.md).
## Using UniClik
1. Run `UniClik.exe` and try the built-in practice area.
2. Press and hold the right button in File Explorer, on the desktop, or in a supported browser.
3. Move over a command. Release the button to select it once.
A quick click without deliberate movement leaves the menu open for normal selection. Hover into submenus before releasing over a command. Disabled rows, separators, and submenu parents do not execute. Escape cancels the gesture. Moving outside a confirmed menu and releasing cancels without clicking the underlying window.
Hold **Alt** to bypass UniClik for a gesture, or press **Ctrl + Alt + U** to pause/resume. The bypass key is configurable. Closing the settings window keeps UniClik in the notification area; use **Quit UniClik** to exit.
**Immediate** activation opens the menu as soon as you press. This takes over the ordinary right-drag gesture in enabled apps. Use bypass or pause when you want to drag with the right button.
**Short hold** activation waits 180 ms by default. Releasing earlier performs a normal right-click. Moving before the delay preserves ordinary right-dragging. The delay and movement threshold are configurable; the threshold scales with the target display's DPI.
## Scope and compatibility
The initial application scope is File Explorer/desktop, Chrome, Edge, and Firefox. You can disable each application group or exclude processes by name. Other applications keep their ordinary input. The practice area is also supported.
UniClik recognizes standard Win32 popup menus and accessible menus exposed through Windows UI Automation. It verifies the target process, menu item, cursor position, and foreground window before invoking the identified command through accessibility. Selection does not synthesize a left-click or move the pointer. If a menu is unknown, inaccessible, or slow to respond, use ordinary selection. Browser-provided menus and website-created menus can expose different accessibility information.
UniClik runs without administrator rights. Windows may block generated input into applications running at a higher integrity level. Touchpad gestures, games, elevated apps, remote desktops, and custom menus require separate compatibility checks.
## Build and test
Windows 10/11 x64 with .NET Framework 4.8 or newer is required. No external NuGet packages are used. The supplied build script uses the Windows .NET Framework compiler; the project file also supports a .NET SDK with .NET Framework reference assemblies installed.
```powershell
.\build.ps1
.\test.ps1
.\test.ps1 -Integration
.\package.ps1
```
The integration suite opens a controlled practice window. Click **Run integration checks** and leave the mouse and keyboard idle until it finishes. It exercises the actual low-level input hook, generated clicks, native and accessible menus, repeated selections, disabled items, submenus, cancellation, bypass, pause, and both activation modes. Practice commands only update counters; they do not rename files or change your clipboard.
Builds go into `dist/`. A build made while UniClik is running is staged as `UniClik.next.exe`, leaving the active executable available. Quit the running application before using a staged build.
## Preferences and startup
Preferences are stored locally at `%LOCALAPPDATA%\UniClik\settings.json`. Apply explicitly saves the draft settings. Pause/resume preserves pending edits in the settings window. Corrupt preferences produce a visible warning and recover to defaults.
Starting with Windows is optional and off initially. Enabling it adds a per-user startup entry for the current executable path. Disable it before moving the executable if you use that option.
## Implementation
The input hook runs on a dedicated thread. A separate MTA worker inspects menus and invokes accessible commands. Each gesture has an identity and deadline, and stale inspections cannot activate a command. UniClik tags the input used to open menus to prevent recursion and checks `SendInput` return values and native structure sizes. A stalled accessibility provider cannot block the input hook.
Relevant Windows references: [context-menu messages](https://learn.microsoft.com/en-us/windows/win32/menurc/wm-contextmenu), [low-level mouse hooks](https://learn.microsoft.com/en-us/windows/win32/winmsg/lowlevelmouseproc), [SendInput](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendinput), and [menu accessibility](https://learn.microsoft.com/en-us/windows/win32/winauto/uiauto-supportmenuitemcontroltype).
## Artwork
The Windows icon contains 16, 20, 24, 32, 40, 48, 64, 128, and 256 pixel versions. The transparent PNG master and README banner are included in `assets/`. They were created with built-in image generation; the exact prompts and final name revision are recorded in `assets/generation-prompts.txt`.
+9
View File
@@ -0,0 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
<PropertyGroup>
<OutputType>WinExe</OutputType><TargetFramework>net48</TargetFramework><UseWindowsForms>true</UseWindowsForms>
<PlatformTarget>x64</PlatformTarget><ApplicationIcon>assets\uniclik-icon.ico</ApplicationIcon><ApplicationManifest>app.manifest</ApplicationManifest>
<EnableDefaultCompileItems>false</EnableDefaultCompileItems><GenerateAssemblyInfo>false</GenerateAssemblyInfo><StartupObject>UniClik.Program</StartupObject>
</PropertyGroup>
<ItemGroup><Compile Include="src\*.cs" /><Reference Include="System.Web.Extensions" /><Reference Include="UIAutomationClient" /><Reference Include="UIAutomationTypes" /><Reference Include="WindowsBase" /></ItemGroup>
<ItemGroup><EmbeddedResource Include="assets\uniclik-icon.png" LogicalName="UniClik.IconPng" /></ItemGroup>
</Project>
+10
View File
@@ -0,0 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="0.1.0.0" name="UniClik.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3"><security><requestedPrivileges><requestedExecutionLevel level="asInvoker" uiAccess="false" /></requestedPrivileges></security></trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1"><application><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" /></application></compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings></application>
</assembly>
+31
View File
@@ -0,0 +1,31 @@
UniClik visual assets
Created with the built-in image_gen tool. The icon has no text and was retained when the user chose the final name UniClik.
1. Icon generation prompt
Use case: logo-brand.
Asset type: application icon concept for a small Windows utility, working name RightFlow.
Primary request: Create one exceptionally clear, polished app icon communicating right mouse button hold, glide to a context-menu command, and release to select.
Composition: square 1024 by 1024 canvas. A single compact mark centered with generous consistent padding. A dark midnight-navy rounded-square app tile with subtly rounded corners. Inside, a bold light-ivory top-down computer mouse silhouette. A clearly separate mint-green upper RIGHT mouse button. At the mouse's right, three short substantial horizontal context-menu bars; one mint selected bar and two ivory bars. Integrate these into a simple balanced symbol, not an illustration of a desktop. Shapes must read well at 32 pixels.
Style: premium native desktop utility icon, crisp geometric edges, restrained slight depth, mostly flat, high contrast. Purposeful, calm, recognizable silhouette.
Background: true transparent alpha outside the rounded-square tile.
Constraints: exactly one icon, no text, no letters, no wordmark, no watermark, no mockup, no surrounding frame, no tiny details, no elaborate arrows or extra pointers. Highlight the RIGHT mouse button, never the left. This is a concept asset, not a screenshot.
2. Initial README banner composition prompt
Use case: compositing.
Asset type: finished GitHub README hero / repository preview image for RightFlow, a planned Windows utility.
Input image: the provided app icon is the identity reference and supporting insert. Reproduce the same mouse-and-context-menu identity faithfully in the hero.
Primary request: design one polished wide README banner explaining the gesture "Hold. Hover. Release." The app will open an existing Windows context menu while the right mouse button is held, then choose the hovered command on release. This is concept artwork, not a screenshot of working software.
Canvas and composition: 1800 by 900 landscape (2:1). Quiet premium midnight-navy backdrop with an extremely subtle soft mint glow near the gesture illustration. Generous 90-pixel outer safe margins. Left 48 percent has clear product typography; right 52 percent has a large coherent diagram/illustration of a mouse and context menu. Everything in one restrained composition, no collage panels.
Identity and typography on left: a small faithful version of the provided icon above or beside the exact large product name "RightFlow". Below the name in two or three elegant large lines write exactly "Hold. Hover. Release." Then smaller supporting line exactly "A smoother right-click for Windows". Along bottom left a quiet line exactly "File Explorer / Desktop / Browsers". A small honest status label "CONCEPT" at top right.
Illustration on right: a refined top-down ivory computer mouse with its upper RIGHT button mint green. To its right, a familiar dark context menu with four rows labeled exactly "Open", "Copy", "Rename", "Properties". "Copy" is the single mint-highlighted row with dark readable text. A clean white pointer rests over the highlighted Copy row. One restrained flowing gesture line leads from the highlighted right mouse button toward Copy. The mouse, menu and pointer make the proposed gesture easy to understand.
Style: beautifully balanced desktop utility branding, crisp geometric shapes, subtle native-app depth, excellent typography, strong contrast. Use midnight navy, warm white and the same mint as the reference. The illustration may be softly shaded but avoid excessive glow.
Constraints: exact requested text only; no extra captions, download buttons, stars, ratings, claims of released support, GitHub logo, Windows logo, watermark, or fabricated app screenshot. Preserve the right-button highlight and matching icon identity. No tiny unreadable text. Full opaque background.
3. Final README banner edit prompt (selected output)
Use case: precise-object-edit.
Asset type: final UniClik GitHub README hero banner.
Input images: Image 1 is the banner to edit. Image 2 is the exact approved icon reference to insert into the banner.
Make only these two changes to Image 1:
1. Replace the product name "RightFlow" with exactly "UniClik" (U n i C l i k, capital U and C). Keep the same bold white type style, baseline, and approximate visual prominence.
2. Replace the simplified small icon at the upper left with a faithful small version of Image 2 including BOTH the computer mouse and its three menu bars. Retain the mint upper RIGHT button and mint middle menu bar, rounded navy tile, original proportions and recognizable geometry.
Keep all other artwork, the large mouse, the context menu, text, spacing, dark navy background, mint highlight, pointer, and the small CONCEPT label unchanged. Preserve the wide 2:1 canvas. Exact remaining text: "Hold. Hover. Release.", "A smoother right-click for Windows", "File Explorer / Desktop / Browsers", "Open", "Copy", "Rename", "Properties", "CONCEPT". Full opaque background.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+26
View File
@@ -0,0 +1,26 @@
param([switch]$Tests)
$ErrorActionPreference = 'Stop'
$projectDirectory = $PSScriptRoot
$frameworkDirectory = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319'
$compilerPath = Join-Path $frameworkDirectory 'csc.exe'
if (-not (Test-Path -LiteralPath $compilerPath)) { throw 'The .NET Framework C# compiler is required. On Windows, install .NET Framework 4.8 developer tools or build UniClik.csproj with a .NET SDK.' }
$outputDirectory = Join-Path $projectDirectory 'dist'
New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null
$sources = @(Get-ChildItem -LiteralPath (Join-Path $projectDirectory 'src') -Filter '*.cs' | ForEach-Object FullName)
$references = @('System.dll','System.Core.dll','System.Drawing.dll','System.Windows.Forms.dll','System.Web.Extensions.dll')
$arguments = @('/nologo','/optimize+','/warn:4','/platform:x64','/codepage:65001')
$arguments += $references | ForEach-Object { '/reference:' + (Join-Path $frameworkDirectory $_) }
$arguments += @('UIAutomationClient.dll','UIAutomationTypes.dll','WindowsBase.dll') | ForEach-Object { '/reference:' + (Join-Path (Join-Path $frameworkDirectory 'WPF') $_) }
$arguments += '/resource:' + (Join-Path $projectDirectory 'assets\uniclik-icon.png') + ',UniClik.IconPng'
$arguments += '/win32icon:' + (Join-Path $projectDirectory 'assets\uniclik-icon.ico')
$arguments += '/win32manifest:' + (Join-Path $projectDirectory 'app.manifest')
$executable = Join-Path $outputDirectory 'UniClik.exe'
if (Get-Process UniClik -ErrorAction SilentlyContinue) { $executable = Join-Path $outputDirectory 'UniClik.next.exe' }
& $compilerPath @arguments '/target:winexe' '/main:UniClik.Program' ('/out:' + $executable) @sources
if ($LASTEXITCODE -ne 0) { throw 'UniClik compilation failed.' }
if ($Tests) {
$testSources = @(Get-ChildItem -LiteralPath (Join-Path $projectDirectory 'tests') -Filter '*.cs' | ForEach-Object FullName)
& $compilerPath @arguments '/target:exe' '/main:UniClik.Tests.Runner' ('/out:' + (Join-Path $outputDirectory 'UniClik.Tests.exe')) @sources @testSources
if ($LASTEXITCODE -ne 0) { throw 'UniClik test compilation failed.' }
}
Write-Output "Built $executable"
+20
View File
@@ -0,0 +1,20 @@
# UniClik implementation plan
## Goal and interaction
Provide a small native Windows tray app for Explorer, desktop, and browser context menus. Press and hold the right mouse button to open the target application's menu; hover over a command and release to invoke it once. Keep a quick click useful for ordinary menu selection.
## Delivered in the 0.1.0 preview
1. A dedicated low-level input-hook thread, scoped process filtering, tagged menu-opening input, and a gesture state machine.
2. A separate accessibility worker that recognizes native and accessible menu items and invokes identified commands without a synthetic left-click.
3. Movement thresholds, submenu handling, cancellation, stale-result deadlines, foreground and pointer checks, and fallback to ordinary selection.
4. A tray app with practice area, explicit Apply settings, immediate/short-hold modes, process exclusions, configurable bypass, pause hotkey, and optional per-user startup.
5. A native multi-resolution icon, transparent master, README preview illustration, portable x64 package, and a dedicated Gitea repository.
6. Unit and actual-input integration coverage. The current validation record is in [validation.md](validation.md).
## Next compatibility milestone
Complete the manual application matrix for Explorer's modern and legacy menus, desktop, Chrome, Edge, and Firefox. Record application versions and results. Add narrowly scoped adapters where evidence shows that a menu exposes a different accessibility shape, with repeat-selection and cancellation checks for each adapter.
Then verify mixed display scaling and touchpad behavior, and promote a stable release only after the target application matrix passes. Keep unsupported custom web menus usable through the ordinary selection fallback.
+39
View File
@@ -0,0 +1,39 @@
# Validation: UniClik 0.1.0 preview
Validated on 2026-10-07, Windows x64 build 10.0.26100.0, .NET Framework 4.8.1.
The combined unit and live input integration run completed with **72 passed, 0 failed**. The integration window used actual Windows low-level hooks and generated right-button down/move/up input, with harmless practice commands. It exercised both native Win32 popups and accessible Windows Forms context menus.
| Check | Result |
| --- | --- |
| Twenty repeated native release selections | Each executed exactly once |
| Ten repeated accessible release selections | Each executed exactly once |
| Engine and menu action counters | 32 actions each |
| Maximum measured mouse hook callback | 3.12 ms; required below 50 ms |
| Quick clicks, disabled rows, separators, submenu parents | No unintended selection |
| Nested submenu selection | Passed |
| Outside release, Escape, focus changes, movement after release | No unintended activation or click-through |
| Bypass, pause during hold, short-hold timing, early right-drag | Passed |
| Preferences, draft state, corrupt settings, native structure sizes | Passed |
| Main window appearance | Visually inspected |
## Application compatibility
The configured target scope is Explorer/desktop, Chrome, Edge, and Firefox. This scope is an implementation target, not proof that every menu in those applications works.
| Target | Status |
| --- | --- |
| Built-in native and accessible practice menus | Live release-to-select verified |
| File Explorer, including Windows 11 modern menu | End-to-end hold/release verification remains outstanding |
| Windows desktop | End-to-end hold/release verification remains outstanding |
| Chrome | End-to-end hold/release verification remains outstanding |
| Edge and Firefox | End-to-end hold/release verification remains outstanding |
| Website-created, elevated, remote-session and touchpad menus | Unverified |
Attempts to inspect the real Explorer and Chrome windows were interrupted by active desktop input. They are not counted as completed compatibility tests. An unknown menu or a command without a usable accessibility action remains open for ordinary selection.
## Reproduce
Run `./test.ps1 -Integration` on Windows, click **Run integration checks**, and leave the mouse and keyboard idle until the fixture closes. Results are saved locally to `artifacts/test-results.txt`. A noninteractive unit run is `./test.ps1`.
For each target application, manually verify: immediate hold/hover/release over a harmless command, quick-click leaves the menu open, disabled and submenu-parent release does not execute, nested selection, Escape, outside release, Alt bypass, short hold, and multi-monitor/DPI behavior. Avoid destructive commands during compatibility testing.
+14
View File
@@ -0,0 +1,14 @@
$ErrorActionPreference = 'Stop'
& (Join-Path $PSScriptRoot 'build.ps1')
$outputDirectory = Join-Path $PSScriptRoot 'dist'
$packageDirectory = Join-Path $outputDirectory ('package-' + [Guid]::NewGuid().ToString('N'))
New-Item -ItemType Directory -Path $packageDirectory | Out-Null
$builtExecutable = Join-Path $outputDirectory 'UniClik.exe'
if (Get-Process UniClik -ErrorAction SilentlyContinue) { $builtExecutable = Join-Path $outputDirectory 'UniClik.next.exe' }
Copy-Item -LiteralPath $builtExecutable -Destination (Join-Path $packageDirectory 'UniClik.exe')
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'README.md'),(Join-Path $PSScriptRoot 'CHANGELOG.md') -Destination $packageDirectory
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'assets') -Destination $packageDirectory -Recurse
Copy-Item -LiteralPath (Join-Path $PSScriptRoot 'docs') -Destination $packageDirectory -Recurse
$archive = Join-Path $outputDirectory 'UniClik-0.1.0-win-x64.zip'
Compress-Archive -LiteralPath (Join-Path $packageDirectory 'UniClik.exe'),(Join-Path $packageDirectory 'README.md'),(Join-Path $packageDirectory 'CHANGELOG.md'),(Join-Path $packageDirectory 'assets'),(Join-Path $packageDirectory 'docs') -DestinationPath $archive -Force
Write-Output "Packaged $archive"
+9
View File
@@ -0,0 +1,9 @@
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("UniClik")]
[assembly: AssemblyDescription("Hold, hover, release: Windows context menus")]
[assembly: AssemblyCompany("Knick")]
[assembly: AssemblyProduct("UniClik")]
[assembly: AssemblyVersion("0.1.0.0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: ComVisible(false)]
+320
View File
@@ -0,0 +1,320 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
namespace UniClik
{
internal sealed class GestureEngine : IDisposable
{
private const int OpenMessage = 0x8001, ProbeMessage = 0x8002, StopMessage = 0x8003, CancelMessage = 0x8004;
private readonly ManualResetEvent ready = new ManualResetEvent(false);
private readonly ConcurrentQueue<MenuHit> hits = new ConcurrentQueue<MenuHit>();
private readonly Dictionary<uint, string> processNames = new Dictionary<uint, string>();
private readonly ConcurrentDictionary<IntPtr, bool> practiceWindows = new ConcurrentDictionary<IntPtr, bool>();
private readonly ConcurrentQueue<string> trace = new ConcurrentQueue<string>();
private readonly uint ownProcess = (uint)Process.GetCurrentProcess().Id;
private readonly Thread thread;
private readonly Action<string> notify;
private Native.HookProc mouseCallback, keyCallback;
private IntPtr mouseHook, keyHook, hostHandle;
private HookHost host;
private MenuProbe probe;
private volatile GestureSession session;
private volatile Settings settings;
private volatile bool stopping;
private Exception startupError;
private bool swallowUp;
private long sequence, lastProbe;
private int completedActions, startedGestures;
private long maximumHookTicks;
internal int CompletedActions { get { return Interlocked.CompareExchange(ref completedActions, 0, 0); } }
internal int StartedGestures { get { return Interlocked.CompareExchange(ref startedGestures, 0, 0); } }
internal double MaximumHookMilliseconds { get { return Interlocked.Read(ref maximumHookTicks) * 1000.0 / Stopwatch.Frequency; } }
internal string LastAdapter { get; private set; }
internal volatile string LastPressDecision = "none";
internal string RecentInputTrace { get { return String.Join(" | ", trace.ToArray()); } }
internal bool Running { get { return hostHandle != IntPtr.Zero && !stopping; } }
internal void RegisterPractice(IntPtr window) { practiceWindows[window] = true; }
internal void UnregisterPractice(IntPtr window) { bool unused; practiceWindows.TryRemove(window, out unused); }
internal GestureEngine(Settings initial, Action<string> message)
{
settings = initial.Clone(); settings.Normalize(); notify = message;
if (Marshal.SizeOf(typeof(Native.INPUT)) != (IntPtr.Size == 8 ? 40 : 28))
throw new InvalidOperationException("The Windows input structure has an invalid size.");
thread = new Thread(Run) { IsBackground = true, Name = "UniClik input hook" };
thread.SetApartmentState(ApartmentState.STA); thread.Start();
if (!ready.WaitOne(5000)) throw new InvalidOperationException("The input hook did not start in time.");
if (startupError != null) throw new InvalidOperationException("Could not install the input hook.", startupError);
}
internal void Update(Settings value)
{
Settings copy = value.Clone(); copy.Normalize(); settings = copy;
if (hostHandle != IntPtr.Zero) Native.PostMessage(hostHandle, CancelMessage, IntPtr.Zero, IntPtr.Zero);
}
private void Run()
{
System.Windows.Forms.Timer timer = null;
try
{
host = new HookHost(this); hostHandle = host.Handle;
probe = new MenuProbe(delegate(MenuHit hit)
{
if (stopping) return;
hits.Enqueue(hit); Native.PostMessage(hostHandle, ProbeMessage, IntPtr.Zero, IntPtr.Zero);
}, CanActivate);
mouseCallback = MouseHook; keyCallback = KeyHook;
IntPtr module = Native.GetModuleHandle(null);
mouseHook = Native.SetWindowsHookEx(Native.WH_MOUSE_LL, mouseCallback, module, 0);
keyHook = Native.SetWindowsHookEx(Native.WH_KEYBOARD_LL, keyCallback, module, 0);
if (mouseHook == IntPtr.Zero || keyHook == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
timer = new System.Windows.Forms.Timer { Interval = 20 };
timer.Tick += delegate { Tick(); }; timer.Start(); ready.Set();
Application.Run();
}
catch (Exception ex) { startupError = ex; Report("Input engine stopped: " + ex.Message); ready.Set(); }
finally
{
stopping = true;
if (timer != null) timer.Dispose();
if (mouseHook != IntPtr.Zero) Native.UnhookWindowsHookEx(mouseHook);
if (keyHook != IntPtr.Zero) Native.UnhookWindowsHookEx(keyHook);
if (probe != null) probe.Dispose();
if (host != null) host.Destroy(); hostHandle = IntPtr.Zero;
}
}
private IntPtr MouseHook(int code, IntPtr message, IntPtr data)
{
long started = Stopwatch.GetTimestamp();
try
{
if (code < 0 || stopping) return Native.CallNextHookEx(mouseHook, code, message, data);
Native.MouseData input = (Native.MouseData)Marshal.PtrToStructure(data, typeof(Native.MouseData));
if (message.ToInt32() == Native.WM_RBUTTONDOWN || message.ToInt32() == Native.WM_RBUTTONUP)
{
trace.Enqueue(message.ToInt32().ToString("X") + ":tag=" + input.ExtraInfo.ToUInt64().ToString("X") + ":swallow=" + swallowUp + ":session=" + (session == null ? "null" : session.Id + "/" + session.Held + "/" + session.Opened));
string unused; while (trace.Count > 18) trace.TryDequeue(out unused);
}
int kind = message.ToInt32();
if (input.ExtraInfo.Equals(Native.InputTag) || (input.Flags & 2) != 0) return Native.CallNextHookEx(mouseHook, code, message, data);
if (kind == Native.WM_RBUTTONDOWN)
{
// A new non-owned down event is a new press. Windows can coalesce a
// rapid injected up with our early synthetic up; never carry that
// gesture's suppression latch into the next physical press.
Cancel(); swallowUp = false;
Settings current = settings;
if (!current.Enabled || Native.GetAsyncKeyState(current.BypassVirtualKey) < 0 || Native.GetAsyncKeyState(1) < 0)
{ LastPressDecision = "paused, bypass held, or left button held"; return Native.CallNextHookEx(mouseHook, code, message, data); }
IntPtr underPointer = Native.WindowFromPoint(input.Point);
IntPtr target = Native.GetAncestor(underPointer, 2);
if (target == IntPtr.Zero) target = underPointer;
string targetClass = Native.ClassName(target);
if (targetClass == "#32768" || targetClass == "Shell_TrayWnd" || targetClass == "Shell_SecondaryTrayWnd")
{ LastPressDecision = "existing menu or taskbar: " + targetClass; return Native.CallNextHookEx(mouseHook, code, message, data); }
uint process = Native.ProcessId(target);
string name;
if (!processNames.TryGetValue(process, out name)) { name = Native.ProcessName(process); processNames[process] = name; }
// Own-process interception is restricted to the practice surface, not the settings controls.
bool practice = false;
if (process == ownProcess)
foreach (IntPtr practiceWindow in practiceWindows.Keys)
if (practiceWindow == underPointer || Native.IsChild(practiceWindow, underPointer)) { practice = true; break; }
if (!current.Allows(name, practice) || (process == ownProcess && !practice))
{ LastPressDecision = "outside supported area: " + name + ", " + targetClass + ", " + Native.ClassName(underPointer); return Native.CallNextHookEx(mouseHook, code, message, data); }
LastPressDecision = "gesture intercepted";
uint dpi = 96;
try { dpi = Native.GetDpiForWindow(target); } catch (EntryPointNotFoundException) { }
session = new GestureSession
{
Id = ++sequence, Started = Environment.TickCount & Int32.MaxValue, ProcessId = process, Target = target,
Origin = input.Point, Point = input.Point, MovementThreshold = Math.Max(3, (int)(current.MovementPixels * dpi / 96)),
OriginalDownDelivered = current.ShortHold
};
Interlocked.Increment(ref startedGestures);
lastProbe = 0;
if (current.ShortHold) return Native.CallNextHookEx(mouseHook, code, message, data);
swallowUp = true;
Native.PostMessage(hostHandle, OpenMessage, new IntPtr(session.Id), IntPtr.Zero);
return new IntPtr(1);
}
if (kind == Native.WM_MOUSEMOVE && session != null)
{
session.Move(input.Point);
if (session.OriginalDownDelivered && !session.Opened && session.Moved) session = null;
}
else if (kind == Native.WM_RBUTTONUP)
{
bool swallow = swallowUp; swallowUp = false;
if (session != null)
{
session.Move(input.Point); session.Held = false; session.ReleasedAt = Clock();
if (session.OriginalDownDelivered && !session.Opened) session = null;
else if (session.Opened) FinishRelease();
}
if (swallow) return new IntPtr(1);
}
else if (kind == Native.WM_LBUTTONDOWN) Cancel();
return Native.CallNextHookEx(mouseHook, code, message, data);
}
catch (Exception ex) { Cancel(); Report("Gesture cancelled: " + ex.Message); return Native.CallNextHookEx(mouseHook, code, message, data); }
finally
{
long elapsed = Stopwatch.GetTimestamp() - started;
if (elapsed > maximumHookTicks) Interlocked.Exchange(ref maximumHookTicks, elapsed);
}
}
private IntPtr KeyHook(int code, IntPtr message, IntPtr data)
{
if (code >= 0 && (message.ToInt32() == Native.WM_KEYDOWN || message.ToInt32() == Native.WM_SYSKEYDOWN))
{
Native.KeyboardData input = (Native.KeyboardData)Marshal.PtrToStructure(data, typeof(Native.KeyboardData));
if (!input.ExtraInfo.Equals(Native.InputTag) && input.Key != 16 && input.Key != 17 && input.Key != 18 && input.Key != 160 && input.Key != 161 && input.Key != 162 && input.Key != 163 && input.Key != 164 && input.Key != 165) Cancel();
}
return Native.CallNextHookEx(keyHook, code, message, data);
}
private void Open(long id)
{
GestureSession current = session;
if (current == null || current.Id != id || current.Cancelled) return;
Native.POINT point; Native.GetCursorPos(out point);
// Never move the cursor or replay a click onto a different control.
if (!GestureSession.CloseTo(point, current.Origin, current.MovementThreshold) || Native.ProcessId(Native.WindowFromPoint(point)) != current.ProcessId)
{
Cancel(); Report("Pointer moved before the menu could open."); return;
}
bool success = current.OriginalDownDelivered ? Native.MouseInput(Native.RIGHTUP) : Native.MouseInput(Native.RIGHTDOWN, Native.RIGHTUP);
if (!success) { Cancel(); Report("Windows blocked the generated click. Check whether the target app is elevated."); return; }
current.Opened = true;
if (current.OriginalDownDelivered) swallowUp = true;
Report("Hold, hover, then release over a command.");
if (!current.Held) FinishRelease();
}
private void Tick()
{
GestureSession current = session;
if (current == null || current.Cancelled) return;
if (!current.Opened)
{
if (current.OriginalDownDelivered && current.Held && Elapsed(current.Started) >= settings.HoldMilliseconds) Open(current.Id);
return;
}
if (!HasTargetFocus(current)) { Cancel(); return; }
if (!current.Held)
{
if (Clock() - current.ReleasedAt > 650) { Cancel(); Report("Menu could not be confirmed in time; choose normally."); }
return;
}
if (Clock() - lastProbe >= 50)
{
lastProbe = Clock();
probe.Request(RequestFor(current, false));
}
}
private void FinishRelease()
{
GestureSession current = session;
if (current == null) return;
if (current.Cancelled || !current.Moved) { session = null; return; }
if (!HasTargetFocus(current)) { Cancel(); return; }
probe.Request(RequestFor(current, true));
}
private static ProbeRequest RequestFor(GestureSession current, bool released)
{
return new ProbeRequest { SessionId = current.Id, ProcessId = current.ProcessId, Point = current.Point, RequestedAt = Clock(), Released = released };
}
private void ProbeCompleted()
{
MenuHit hit;
while (hits.TryDequeue(out hit))
{
GestureSession current = session;
if (hit.Activated)
{
Interlocked.Increment(ref completedActions);
if (current != null && current.Id == hit.SessionId) session = null;
Report("Command selected on release."); continue;
}
if (current == null || current.Id != hit.SessionId || current.Cancelled || Clock() - hit.RequestedAt > 180) continue;
if (hit.MenuExists)
{
LastAdapter = hit.Adapter;
if (hit.HitWindow != IntPtr.Zero)
{
IntPtr root = Native.GetAncestor(hit.HitWindow, 2);
if (root != current.Target) current.KnownMenuWindow = root == IntPtr.Zero ? hit.HitWindow : root;
}
}
if (!hit.Released || current.Held) continue;
if (!HasTargetFocus(current)) { Cancel(); continue; }
Native.POINT pointer; Native.GetCursorPos(out pointer);
if (!GestureSession.CloseTo(pointer, hit.Point, 2)) { Cancel(); continue; }
if (!hit.MenuExists && current.KnownMenuWindow != IntPtr.Zero && Native.IsWindowVisible(current.KnownMenuWindow)) hit.Kind = HitKind.Outside;
ReleaseAction action = current.ActionFor(hit.Kind);
session = null; // Consume the gesture before injecting: exactly one activation.
if (action == ReleaseAction.Select)
{
IntPtr underPointer = Native.WindowFromPoint(pointer);
if (underPointer == IntPtr.Zero || Native.ProcessId(underPointer) != current.ProcessId || (hit.HitWindow != IntPtr.Zero && underPointer != hit.HitWindow))
{
Report("The menu changed; choose normally."); continue;
}
Report("This command could not be invoked through accessibility; choose normally.");
}
else if (action == ReleaseAction.Cancel && hit.MenuExists) { Native.Escape(); Report("Gesture cancelled."); }
else if (action == ReleaseAction.Cancel && current.KnownMenuWindow != IntPtr.Zero) { Native.Escape(); Report("Gesture cancelled."); }
else Report(hit.Kind == HitKind.Submenu ? "Submenu left open; choose a command." : "Menu left open for ordinary selection.");
}
}
private bool CanActivate(ProbeRequest request, MenuHit hit)
{
GestureSession current = session;
if (stopping || current == null || current.Id != request.SessionId || current.Held || current.Cancelled || !current.Moved || !current.Opened || Clock() - current.ReleasedAt > 500 || !HasTargetFocus(current)) return false;
Native.POINT point; Native.GetCursorPos(out point);
if (!GestureSession.CloseTo(point, request.Point, 2)) return false;
IntPtr window = Native.WindowFromPoint(point);
return window != IntPtr.Zero && window == hit.HitWindow && Native.ProcessId(window) == current.ProcessId;
}
private static bool HasTargetFocus(GestureSession current)
{
IntPtr foreground = Native.GetForegroundWindow();
if (Native.ProcessId(foreground) != current.ProcessId) return false;
IntPtr root = Native.GetAncestor(foreground, 2);
return foreground == current.Target || root == current.Target || foreground == current.KnownMenuWindow || root == current.KnownMenuWindow;
}
private static long Clock() { return Stopwatch.GetTimestamp() * 1000 / Stopwatch.Frequency; }
private static int Elapsed(long start) { return ((Environment.TickCount & Int32.MaxValue) - (int)start) & Int32.MaxValue; }
private void Cancel() { GestureSession current = session; if (current != null) current.Cancelled = true; session = null; }
private void Report(string text) { if (notify != null) notify(text); }
public void Dispose()
{
if (stopping) return;
Cancel();
stopping = true;
if (hostHandle != IntPtr.Zero) Native.PostMessage(hostHandle, StopMessage, IntPtr.Zero, IntPtr.Zero);
thread.Join(1000);
}
private sealed class HookHost : NativeWindow
{
private readonly GestureEngine engine;
internal HookHost(GestureEngine owner)
{
engine = owner;
CreateHandle(new CreateParams { Caption = "UniClik input", Parent = new IntPtr(-3) });
}
internal void Destroy() { DestroyHandle(); }
protected override void WndProc(ref Message message)
{
if (message.Msg == OpenMessage) engine.Open(message.WParam.ToInt64());
else if (message.Msg == ProbeMessage) engine.ProbeCompleted();
else if (message.Msg == CancelMessage) engine.Cancel();
else if (message.Msg == StopMessage) { engine.Cancel(); Application.ExitThread(); }
base.WndProc(ref message);
}
}
}
}
+33
View File
@@ -0,0 +1,33 @@
using System;
namespace UniClik
{
internal enum HitKind { Unknown, Outside, Disabled, Separator, Submenu, Command }
internal enum ReleaseAction { LeaveOpen, Cancel, Select }
internal sealed class GestureSession
{
internal long Id, Started, ReleasedAt;
internal uint ProcessId;
internal IntPtr Target, KnownMenuWindow;
internal Native.POINT Origin, Point;
internal int MovementThreshold;
internal bool Held = true, Moved, Opened, Cancelled, OriginalDownDelivered;
internal void Move(Native.POINT point)
{
Point = point;
long dx = (long)point.X - Origin.X, dy = (long)point.Y - Origin.Y;
if (dx * dx + dy * dy >= (long)MovementThreshold * MovementThreshold) Moved = true;
}
internal ReleaseAction ActionFor(HitKind kind)
{
if (Cancelled || !Opened || !Moved) return ReleaseAction.LeaveOpen;
if (kind == HitKind.Command) return ReleaseAction.Select;
if (kind == HitKind.Outside) return ReleaseAction.Cancel;
return ReleaseAction.LeaveOpen;
}
internal static bool CloseTo(Native.POINT a, Native.POINT b, int tolerance)
{
return Math.Abs((long)a.X - b.X) <= tolerance && Math.Abs((long)a.Y - b.Y) <= tolerance;
}
}
}
+137
View File
@@ -0,0 +1,137 @@
using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
namespace UniClik
{
internal sealed class MainForm : Form
{
internal readonly PracticeSurface Practice = new PracticeSurface();
internal event Action ToggleRequested;
internal event Action<Settings, bool> ApplyRequested;
internal event Action ExitRequested;
private readonly CheckBox explorer = new CheckBox(), chrome = new CheckBox(), edge = new CheckBox(), firefox = new CheckBox(), startup = new CheckBox();
private readonly ComboBox activation = new ComboBox(), bypass = new ComboBox();
private readonly NumericUpDown hold = new NumericUpDown(), movement = new NumericUpDown();
private readonly TextBox exclusions = new TextBox();
private readonly Label status = new Label(), result = new Label(), state = new Label();
private readonly Button toggle = new Button();
private Settings applied;
private bool exitAllowed;
private readonly Image logo;
internal static readonly uint ShowMessage = Native.RegisterWindowMessage("UniClik.ShowWindow.1");
private static readonly Color Background = Color.FromArgb(12, 19, 32), Muted = Color.FromArgb(160, 180, 200), Mint = Color.FromArgb(132, 245, 199);
internal MainForm(Settings settings, bool startsWithWindows)
{
Text = "UniClik"; ClientSize = new Size(820, 760); MinimumSize = new Size(750, 780);
Font = new Font("Segoe UI", 10); BackColor = Background; ForeColor = Color.FromArgb(231, 237, 244);
AutoScaleMode = AutoScaleMode.Font; StartPosition = FormStartPosition.CenterScreen;
Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("UniClik.IconPng"))
if (stream != null) using (Bitmap image = new Bitmap(stream)) logo = new Bitmap(image);
TableLayoutPanel layout = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 1, Padding = new Padding(28), AutoScroll = true };
Controls.Add(layout);
TableLayoutPanel header = new TableLayoutPanel { Height = 86, Dock = DockStyle.Top, ColumnCount = 3 };
header.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 82)); header.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100)); header.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 140));
PictureBox mark = new PictureBox { Image = logo, SizeMode = PictureBoxSizeMode.Zoom, Size = new Size(66, 66), Margin = new Padding(0, 0, 16, 0) };
FlowLayoutPanel title = new FlowLayoutPanel { Dock = DockStyle.Fill, FlowDirection = FlowDirection.TopDown, WrapContents = false, Margin = new Padding(0) };
title.Controls.Add(new Label { Text = "UniClik", Font = new Font("Segoe UI", 27, FontStyle.Bold), AutoSize = true, Margin = new Padding(0) });
state.AutoSize = true; state.Margin = new Padding(3, 0, 0, 0); title.Controls.Add(state);
StyleButton(toggle, false); toggle.Width = 126; toggle.Height = 38; toggle.Margin = new Padding(0, 15, 0, 0); toggle.Click += delegate { if (ToggleRequested != null) ToggleRequested(); };
header.Controls.Add(mark, 0, 0); header.Controls.Add(title, 1, 0); header.Controls.Add(toggle, 2, 0); Add(layout, header, 90);
Label instructions = new Label { Text = "Hold. Hover. Release.\nOpen a context menu while holding the right button, then let go over a command.", Dock = DockStyle.Fill, ForeColor = Muted, Margin = new Padding(0, 6, 0, 12) }; Add(layout, instructions, 64);
Practice.Dock = DockStyle.Fill; Practice.Margin = new Padding(0); Add(layout, Practice, 132);
Practice.Selected += delegate(string command) { result.Text = "Selected: " + command + " | Practice selections: " + Practice.SelectionCount; };
result.Text = "Ready to practice. A quick click leaves the menu open."; result.ForeColor = Mint; result.Dock = DockStyle.Fill; result.Margin = new Padding(0, 8, 0, 0); Add(layout, result, 38);
TableLayoutPanel settingsGrid = new TableLayoutPanel { Dock = DockStyle.Fill, ColumnCount = 2, Margin = new Padding(0, 12, 0, 0) };
settingsGrid.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 160)); settingsGrid.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
FlowLayoutPanel apps = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = true, Margin = new Padding(0) };
foreach (CheckBox checkbox in new[] { explorer, chrome, edge, firefox }) { checkbox.AutoSize = true; checkbox.Margin = new Padding(0, 3, 14, 0); apps.Controls.Add(checkbox); }
explorer.Text = "Explorer + desktop"; chrome.Text = "Chrome"; edge.Text = "Edge"; firefox.Text = "Firefox";
Row(settingsGrid, "Supported apps", apps, 42);
activation.DropDownStyle = ComboBoxStyle.DropDownList; activation.Items.AddRange(new object[] { "Immediate", "Short hold - preserves normal right-drag" }); StyleInput(activation); activation.Dock = DockStyle.Fill;
Row(settingsGrid, "Open menu", activation, 42);
FlowLayoutPanel timing = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false, Margin = new Padding(0) };
hold.Minimum = 100; hold.Maximum = 600; hold.Increment = 20; hold.Width = 76; StyleInput(hold);
movement.Minimum = 3; movement.Maximum = 24; movement.Width = 65; StyleInput(movement);
timing.Controls.Add(hold); timing.Controls.Add(new Label { Text = "ms hold Move", AutoSize = true, Margin = new Padding(3, 5, 6, 0), ForeColor = Muted }); timing.Controls.Add(movement); timing.Controls.Add(new Label { Text = "px to select (scaled for display)", AutoSize = true, Margin = new Padding(3, 5, 0, 0), ForeColor = Muted });
Row(settingsGrid, "Gesture tuning", timing, 42);
bypass.DropDownStyle = ComboBoxStyle.DropDownList; bypass.Items.AddRange(new object[] { "Alt", "Control", "Shift" }); StyleInput(bypass); bypass.Dock = DockStyle.Left; bypass.Width = 132;
Row(settingsGrid, "Hold key to bypass", bypass, 42);
StyleInput(exclusions); exclusions.Dock = DockStyle.Fill; exclusions.AccessibleName = "Excluded process names";
Row(settingsGrid, "Exclude processes", exclusions, 42);
startup.Text = "Start UniClik when I sign in"; startup.AutoSize = true; startup.Dock = DockStyle.Fill; startup.Margin = new Padding(0, 4, 0, 0);
Row(settingsGrid, "Startup", startup, 36); Add(layout, settingsGrid, 265);
FlowLayoutPanel footer = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false, Margin = new Padding(0, 12, 0, 0) };
Button apply = new Button { Text = "Apply settings", Width = 144, Height = 38 }; StyleButton(apply, true);
apply.Click += delegate { if (ApplyRequested != null) ApplyRequested(ReadDraft(), startup.Checked); };
Button reset = new Button { Text = "Reset changes", Width = 126, Height = 38 }; StyleButton(reset, false); reset.Click += delegate { LoadDraft(applied, Startup.IsEnabled); };
Button exit = new Button { Text = "Quit UniClik", Width = 126, Height = 38 }; StyleButton(exit, false); exit.Click += delegate { if (ExitRequested != null) ExitRequested(); };
footer.Controls.Add(apply); footer.Controls.Add(reset); footer.Controls.Add(exit); Add(layout, footer, 56);
status.Text = "Ctrl + Alt + U pauses or resumes. Closing this window keeps UniClik in the tray."; status.ForeColor = Muted; status.Dock = DockStyle.Fill; status.Margin = new Padding(0, 7, 0, 0); Add(layout, status, 46);
activation.SelectedIndexChanged += delegate { hold.Enabled = activation.SelectedIndex == 1; };
LoadDraft(settings, startsWithWindows); ReflectEnabled(settings.Enabled);
}
private static void Add(TableLayoutPanel parent, Control control, int height)
{
int row = parent.RowCount++; parent.RowStyles.Add(new RowStyle(SizeType.Absolute, height)); parent.Controls.Add(control, 0, row);
}
private static void Row(TableLayoutPanel parent, string caption, Control input, int height)
{
int row = parent.RowCount++; parent.RowStyles.Add(new RowStyle(SizeType.Absolute, height));
parent.Controls.Add(new Label { Text = caption, Dock = DockStyle.Fill, ForeColor = Muted, Margin = new Padding(0, 6, 0, 0) }, 0, row); parent.Controls.Add(input, 1, row);
}
private static void StyleInput(Control input) { input.BackColor = Color.FromArgb(27, 39, 57); input.ForeColor = Color.FromArgb(231, 237, 244); }
private static void StyleButton(Button button, bool primary)
{
button.FlatStyle = FlatStyle.Flat; button.FlatAppearance.BorderColor = Color.FromArgb(66, 91, 112);
button.BackColor = primary ? Mint : Color.FromArgb(27, 39, 57); button.ForeColor = primary ? Background : Color.FromArgb(231, 237, 244); button.Cursor = Cursors.Hand; button.Margin = new Padding(0, 0, 12, 0);
}
private Settings ReadDraft()
{
Settings draft = applied.Clone(); draft.Explorer = explorer.Checked; draft.Chrome = chrome.Checked; draft.Edge = edge.Checked; draft.Firefox = firefox.Checked;
draft.ShortHold = activation.SelectedIndex == 1; draft.HoldMilliseconds = (int)hold.Value; draft.MovementPixels = (int)movement.Value;
draft.BypassKey = Convert.ToString(bypass.SelectedItem); draft.ExcludedProcesses = exclusions.Text; return draft;
}
private void LoadDraft(Settings settings, bool startsWithWindows)
{
applied = settings.Clone(); explorer.Checked = settings.Explorer; chrome.Checked = settings.Chrome; edge.Checked = settings.Edge; firefox.Checked = settings.Firefox;
activation.SelectedIndex = settings.ShortHold ? 1 : 0; hold.Value = settings.HoldMilliseconds; movement.Value = settings.MovementPixels;
bypass.SelectedItem = settings.BypassKey; exclusions.Text = settings.ExcludedProcesses; startup.Checked = startsWithWindows;
}
internal void Applied(Settings settings, bool startsWithWindows) { LoadDraft(settings, startsWithWindows); ReflectEnabled(settings.Enabled); }
internal void ReflectEnabled(bool enabled)
{
if (applied != null) applied.Enabled = enabled;
state.Text = enabled ? "Active in your supported apps" : "Paused - ordinary right-click is active"; state.ForeColor = enabled ? Mint : Muted; toggle.Text = enabled ? "Pause" : "Resume";
}
internal void ShowStatus(string message) { status.Text = message; }
internal void Reveal() { Show(); WindowState = FormWindowState.Normal; Activate(); }
internal void AllowExit() { exitAllowed = true; }
protected override void OnFormClosing(FormClosingEventArgs e)
{
if (!exitAllowed && e.CloseReason == CloseReason.UserClosing) { e.Cancel = true; Hide(); } base.OnFormClosing(e);
}
protected override void WndProc(ref Message message)
{
if (message.Msg == ShowMessage) Reveal();
if (message.Msg == Native.WM_HOTKEY && message.WParam.ToInt32() == 1 && ToggleRequested != null) ToggleRequested();
base.WndProc(ref message);
}
protected override void OnHandleCreated(EventArgs e)
{
base.OnHandleCreated(e); Native.RegisterHotKey(Handle, 1, 0x4003, 0x55);
}
protected override void Dispose(bool disposing)
{
if (IsHandleCreated) Native.UnregisterHotKey(Handle, 1);
if (disposing && logo != null) logo.Dispose(); base.Dispose(disposing);
}
}
}
+152
View File
@@ -0,0 +1,152 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Windows.Automation;
namespace UniClik
{
internal sealed class MenuHit
{
internal long SessionId, RequestedAt;
internal Native.POINT Point;
internal HitKind Kind;
internal bool MenuExists, Released;
internal bool Activated;
internal IntPtr HitWindow;
internal string Adapter = "none";
}
internal sealed class ProbeRequest
{
internal long SessionId, RequestedAt;
internal uint ProcessId;
internal Native.POINT Point;
internal bool Released;
}
internal sealed class MenuProbe : IDisposable
{
private readonly AutoResetEvent wake = new AutoResetEvent(false);
private readonly Action<MenuHit> callback;
private readonly Func<ProbeRequest, MenuHit, bool> canActivate;
private readonly Thread thread;
private ProbeRequest pending;
private volatile bool stopping;
internal MenuProbe(Action<MenuHit> completed, Func<ProbeRequest, MenuHit, bool> validate)
{
callback = completed; canActivate = validate;
thread = new Thread(Run) { IsBackground = true, Name = "UniClik menu inspection" };
thread.SetApartmentState(ApartmentState.MTA); thread.Start();
}
internal void Request(ProbeRequest request) { Interlocked.Exchange(ref pending, request); wake.Set(); }
private void Run()
{
while (!stopping)
{
wake.WaitOne();
ProbeRequest request = Interlocked.Exchange(ref pending, null);
if (request == null || stopping) continue;
try
{
MenuHit hit = Inspect(request);
if (request.Released && hit.Kind == HitKind.Command && !stopping && canActivate(request, hit))
hit.Activated = Activate(request, hit);
if (!stopping) callback(hit);
}
catch { if (!stopping) callback(new MenuHit { SessionId = request.SessionId, Point = request.Point, RequestedAt = request.RequestedAt, Released = request.Released, Kind = HitKind.Unknown }); }
}
}
private bool Activate(ProbeRequest request, MenuHit hit)
{
AutomationElement command = AutomationElement.FromPoint(new System.Windows.Point(request.Point.X, request.Point.Y));
TreeWalker walker = TreeWalker.ControlViewWalker;
for (int depth = 0; command != null && depth < 10; depth++)
{
AutomationElement.AutomationElementInformation current = command.Current;
if (current.ProcessId != request.ProcessId || !current.IsEnabled) return false;
if (current.ControlType == ControlType.MenuItem || current.ControlType == ControlType.Button || current.ControlType == ControlType.CheckBox)
{
object pattern;
if (command.TryGetCurrentPattern(InvokePattern.Pattern, out pattern))
{
if (!canActivate(request, hit)) return false;
((InvokePattern)pattern).Invoke(); return true;
}
if (command.TryGetCurrentPattern(TogglePattern.Pattern, out pattern))
{
if (!canActivate(request, hit)) return false;
((TogglePattern)pattern).Toggle(); return true;
}
if (command.TryGetCurrentPattern(SelectionItemPattern.Pattern, out pattern))
{
if (!canActivate(request, hit)) return false;
((SelectionItemPattern)pattern).Select(); return true;
}
return false;
}
command = walker.GetParent(command);
}
return false;
}
internal static MenuHit Inspect(ProbeRequest request)
{
MenuHit hit = new MenuHit { SessionId = request.SessionId, Point = request.Point, RequestedAt = request.RequestedAt, Released = request.Released, Kind = HitKind.Unknown };
List<IntPtr> menus = new List<IntPtr>();
Native.EnumWindows(delegate(IntPtr hwnd, IntPtr unused)
{
if (Native.IsWindowVisible(hwnd) && Native.ProcessId(hwnd) == request.ProcessId && Native.ClassName(hwnd) == "#32768") menus.Add(hwnd);
return true;
}, IntPtr.Zero);
if (menus.Count > 0)
{
hit.MenuExists = true; hit.Kind = HitKind.Outside; hit.Adapter = "Win32 menu";
foreach (IntPtr hwnd in menus)
{
Native.RECT bounds;
if (!Native.GetWindowRect(hwnd, out bounds) || !bounds.Contains(request.Point)) continue;
hit.HitWindow = hwnd; hit.Kind = HitKind.Unknown;
Native.MENUBARINFO info = new Native.MENUBARINFO { Size = (uint)System.Runtime.InteropServices.Marshal.SizeOf(typeof(Native.MENUBARINFO)) };
if (!Native.GetMenuBarInfo(hwnd, -4, 0, ref info) || info.Menu == IntPtr.Zero) continue;
int count = Native.GetMenuItemCount(info.Menu);
for (uint i = 0; i < count; i++)
{
Native.RECT item;
if (!Native.GetMenuItemRect(IntPtr.Zero, info.Menu, i, out item) || !item.Contains(request.Point)) continue;
uint flags = Native.GetMenuState(info.Menu, i, 0x400);
if (flags == UInt32.MaxValue) break;
hit.Kind = (flags & 0x800) != 0 ? HitKind.Separator : (flags & 3) != 0 ? HitKind.Disabled : Native.GetSubMenu(info.Menu, (int)i) != IntPtr.Zero ? HitKind.Submenu : HitKind.Command;
return hit;
}
}
if (hit.Kind != HitKind.Unknown) return hit;
}
AutomationElement element = AutomationElement.FromPoint(new System.Windows.Point(request.Point.X, request.Point.Y));
AutomationElement command = null, menu = null;
bool submenu = false, disabled = false, separator = false;
TreeWalker walker = TreeWalker.ControlViewWalker;
for (int depth = 0; element != null && depth < 18; depth++)
{
AutomationElement.AutomationElementInformation current = element.Current;
if (current.ProcessId != request.ProcessId) break;
if (current.ControlType == ControlType.Menu) { menu = element; break; }
if (current.ControlType == ControlType.Separator) separator = true;
if (command == null && (current.ControlType == ControlType.MenuItem || current.ControlType == ControlType.Button || current.ControlType == ControlType.CheckBox))
{
command = element; disabled = !current.IsEnabled;
object expand;
if (element.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out expand))
submenu = ((ExpandCollapsePattern)expand).Current.ExpandCollapseState != ExpandCollapseState.LeafNode;
}
element = walker.GetParent(element);
}
if (menu != null)
{
hit.MenuExists = true; hit.Adapter = "Accessible menu";
hit.HitWindow = Native.WindowFromPoint(request.Point);
hit.Kind = separator ? HitKind.Separator : command == null ? HitKind.Unknown : disabled ? HitKind.Disabled : submenu ? HitKind.Submenu : HitKind.Command;
}
return hit;
}
public void Dispose() { stopping = true; wake.Set(); /* A stalled provider never blocks shutdown or injects input. */ }
}
}
+155
View File
@@ -0,0 +1,155 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace UniClik
{
internal static class Native
{
internal const int WH_MOUSE_LL = 14, WH_KEYBOARD_LL = 13;
internal const int WM_MOUSEMOVE = 0x200, WM_LBUTTONDOWN = 0x201, WM_RBUTTONDOWN = 0x204, WM_RBUTTONUP = 0x205;
internal const int WM_KEYDOWN = 0x100, WM_SYSKEYDOWN = 0x104, WM_HOTKEY = 0x312;
internal const uint RIGHTDOWN = 0x8, RIGHTUP = 0x10, LEFTDOWN = 0x2, LEFTUP = 0x4;
internal static readonly UIntPtr InputTag = new UIntPtr(0x55434C4B);
internal delegate IntPtr HookProc(int code, IntPtr message, IntPtr data);
internal delegate bool EnumProc(IntPtr hwnd, IntPtr parameter);
[StructLayout(LayoutKind.Sequential)] internal struct POINT
{
internal int X, Y;
internal POINT(int x, int y) { X = x; Y = y; }
}
[StructLayout(LayoutKind.Sequential)] internal struct RECT
{
internal int Left, Top, Right, Bottom;
internal bool Contains(POINT p) { return p.X >= Left && p.X < Right && p.Y >= Top && p.Y < Bottom; }
}
[StructLayout(LayoutKind.Sequential)] internal struct MouseData
{
internal POINT Point;
internal uint MouseDataValue, Flags, Time;
internal UIntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)] internal struct KeyboardData
{
internal uint Key, Scan, Flags, Time;
internal UIntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)] internal struct MOUSEINPUT
{
internal int Dx, Dy;
internal uint Data, Flags, Time;
internal UIntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Sequential)] internal struct KEYBDINPUT
{
internal ushort Key, Scan;
internal uint Flags, Time;
internal UIntPtr ExtraInfo;
}
[StructLayout(LayoutKind.Explicit)] internal struct InputUnion
{
[FieldOffset(0)] internal MOUSEINPUT Mouse;
[FieldOffset(0)] internal KEYBDINPUT Keyboard;
}
[StructLayout(LayoutKind.Sequential)] internal struct INPUT
{
internal uint Type;
internal InputUnion Data;
}
[StructLayout(LayoutKind.Sequential)] internal struct MENUBARINFO
{
internal uint Size;
internal RECT Rectangle;
internal IntPtr Menu, MenuWindow;
internal uint Flags;
}
[StructLayout(LayoutKind.Sequential)] internal struct GUITHREADINFO
{
internal uint Size, Flags;
internal IntPtr Active, Focus, Capture, MenuOwner, MoveSize, Caret;
internal RECT CaretRectangle;
}
[DllImport("user32.dll", SetLastError = true)] internal static extern IntPtr SetWindowsHookEx(int type, HookProc callback, IntPtr module, uint thread);
[DllImport("user32.dll", SetLastError = true)] internal static extern bool UnhookWindowsHookEx(IntPtr hook);
[DllImport("user32.dll")] internal static extern IntPtr CallNextHookEx(IntPtr hook, int code, IntPtr message, IntPtr data);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern IntPtr GetModuleHandle(string name);
[DllImport("user32.dll", SetLastError = true)] internal static extern uint SendInput(uint count, INPUT[] inputs, int size);
[DllImport("user32.dll")] internal static extern IntPtr WindowFromPoint(POINT point);
[DllImport("user32.dll")] internal static extern IntPtr GetAncestor(IntPtr hwnd, uint flags);
[DllImport("user32.dll")] internal static extern uint GetWindowThreadProcessId(IntPtr hwnd, out uint process);
[DllImport("user32.dll")] internal static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")] internal static extern bool GetCursorPos(out POINT point);
[DllImport("user32.dll")] internal static extern short GetAsyncKeyState(int key);
[DllImport("user32.dll")] internal static extern bool IsWindowVisible(IntPtr hwnd);
[DllImport("user32.dll")] internal static extern bool IsWindow(IntPtr hwnd);
[DllImport("user32.dll")] internal static extern bool IsChild(IntPtr parent, IntPtr child);
[DllImport("user32.dll")] internal static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern uint RegisterWindowMessage(string name);
[DllImport("user32.dll")] internal static extern IntPtr CreatePopupMenu();
[DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern bool AppendMenu(IntPtr menu, uint flags, UIntPtr command, string label);
[DllImport("user32.dll")] internal static extern bool DestroyMenu(IntPtr menu);
[DllImport("user32.dll")] internal static extern uint TrackPopupMenuEx(IntPtr menu, uint flags, int x, int y, IntPtr owner, IntPtr parameters);
[DllImport("user32.dll")] internal static extern bool SetForegroundWindow(IntPtr hwnd);
[DllImport("user32.dll")] internal static extern bool EnumWindows(EnumProc callback, IntPtr parameter);
[DllImport("user32.dll", CharSet = CharSet.Unicode)] internal static extern int GetClassName(IntPtr hwnd, StringBuilder value, int length);
[DllImport("user32.dll")] internal static extern bool GetWindowRect(IntPtr hwnd, out RECT rectangle);
[DllImport("user32.dll")] internal static extern bool GetMenuBarInfo(IntPtr hwnd, int objectId, int item, ref MENUBARINFO info);
[DllImport("user32.dll")] internal static extern int GetMenuItemCount(IntPtr menu);
[DllImport("user32.dll")] internal static extern uint GetMenuState(IntPtr menu, uint item, uint flags);
[DllImport("user32.dll")] internal static extern IntPtr GetSubMenu(IntPtr menu, int item);
[DllImport("user32.dll")] internal static extern bool GetMenuItemRect(IntPtr hwnd, IntPtr menu, uint item, out RECT rectangle);
[DllImport("user32.dll")] internal static extern bool GetGUIThreadInfo(uint thread, ref GUITHREADINFO info);
[DllImport("user32.dll")] internal static extern uint GetDpiForWindow(IntPtr hwnd);
[DllImport("user32.dll")] internal static extern bool RegisterHotKey(IntPtr hwnd, int id, uint modifiers, uint key);
[DllImport("user32.dll")] internal static extern bool UnregisterHotKey(IntPtr hwnd, int id);
[DllImport("user32.dll", SetLastError = true)] internal static extern bool PostMessage(IntPtr hwnd, int message, IntPtr wparam, IntPtr lparam);
[DllImport("kernel32.dll", SetLastError = true)] internal static extern IntPtr OpenProcess(uint access, bool inherit, uint process);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)] internal static extern bool QueryFullProcessImageName(IntPtr process, uint flags, StringBuilder name, ref uint size);
[DllImport("kernel32.dll")] internal static extern bool CloseHandle(IntPtr handle);
internal static uint ProcessId(IntPtr hwnd) { uint id; GetWindowThreadProcessId(hwnd, out id); return id; }
internal static string ClassName(IntPtr hwnd)
{
StringBuilder name = new StringBuilder(256);
GetClassName(hwnd, name, name.Capacity);
return name.ToString();
}
internal static string ProcessName(uint id)
{
IntPtr handle = OpenProcess(0x1000, false, id);
if (handle == IntPtr.Zero) return "";
try
{
StringBuilder name = new StringBuilder(1024); uint length = (uint)name.Capacity;
return QueryFullProcessImageName(handle, 0, name, ref length) ? System.IO.Path.GetFileNameWithoutExtension(name.ToString()).ToLowerInvariant() : "";
}
finally { CloseHandle(handle); }
}
internal static bool MouseInput(params uint[] flags)
{
INPUT[] inputs = new INPUT[flags.Length];
for (int i = 0; i < inputs.Length; i++)
inputs[i].Data.Mouse = new MOUSEINPUT { Flags = flags[i], ExtraInfo = InputTag };
uint sent = SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
if (sent != inputs.Length && sent > 0 && inputs.Length > 1)
{
INPUT[] cleanup = new INPUT[1];
cleanup[0].Data.Mouse = new MOUSEINPUT { Flags = flags[0] == RIGHTDOWN ? RIGHTUP : LEFTUP, ExtraInfo = InputTag };
SendInput(1, cleanup, Marshal.SizeOf(typeof(INPUT)));
}
return sent == inputs.Length;
}
internal static bool Escape()
{
INPUT[] inputs = new INPUT[2];
for (int i = 0; i < 2; i++)
{
inputs[i].Type = 1;
inputs[i].Data.Keyboard = new KEYBDINPUT { Key = 27, Flags = i == 0 ? 0u : 2u, ExtraInfo = InputTag };
}
return SendInput(2, inputs, Marshal.SizeOf(typeof(INPUT))) == 2;
}
}
}
+73
View File
@@ -0,0 +1,73 @@
using System;
using System.Drawing;
using System.Windows.Forms;
namespace UniClik
{
internal sealed class PracticeSurface : Panel
{
internal event Action<string> Selected;
internal int SelectionCount { get; private set; }
internal uint LastCommand { get; private set; }
internal bool AccessibleMenu { get; set; }
private readonly ContextMenuStrip accessibleMenu;
internal PracticeSurface()
{
DoubleBuffered = true; BackColor = Color.FromArgb(23, 38, 48); Cursor = Cursors.Hand;
AccessibleName = "UniClik practice area";
accessibleMenu = new ContextMenuStrip();
accessibleMenu.Items.Add("Copy", null, delegate { Record(101, "Copy"); });
accessibleMenu.Items.Add("Rename", null, delegate { Record(102, "Rename"); });
accessibleMenu.Items.Add(new ToolStripMenuItem("Unavailable") { Enabled = false });
accessibleMenu.Items.Add(new ToolStripSeparator());
ToolStripMenuItem more = new ToolStripMenuItem("More actions");
more.DropDownItems.Add("Nested command", null, delegate { Record(105, "Nested command"); });
accessibleMenu.Items.Add(more);
accessibleMenu.Items.Add("Properties", null, delegate { Record(104, "Properties"); });
}
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
using (Pen border = new Pen(Color.FromArgb(78, 128, 112))) e.Graphics.DrawRectangle(border, 0, 0, Width - 1, Height - 1);
using (Font heading = new Font("Segoe UI", 16, FontStyle.Bold)) TextRenderer.DrawText(e.Graphics, "Try the gesture here", heading, new Rectangle(12, 14, Width - 24, 36), Color.FromArgb(132, 245, 199), TextFormatFlags.HorizontalCenter);
TextRenderer.DrawText(e.Graphics, "Hold right button > hover a command > release", Font, new Rectangle(12, 58, Width - 24, 28), Color.FromArgb(222, 232, 239), TextFormatFlags.HorizontalCenter);
TextRenderer.DrawText(e.Graphics, "Practice commands only update the result below.", Font, new Rectangle(12, 90, Width - 24, 24), Color.FromArgb(156, 181, 191), TextFormatFlags.HorizontalCenter);
}
protected override void WndProc(ref Message message)
{
if (message.Msg == 0x7B)
{
long coordinates = message.LParam.ToInt64();
int x = (short)(coordinates & 0xFFFF), y = (short)((coordinates >> 16) & 0xFFFF);
if (x == -1 && y == -1) { Point center = PointToScreen(new Point(Width / 2, Height / 2)); x = center.X; y = center.Y; }
Native.SetForegroundWindow(FindForm().Handle);
if (AccessibleMenu) { accessibleMenu.Show(new Point(x, y)); return; }
IntPtr menu = Native.CreatePopupMenu(), submenu = Native.CreatePopupMenu();
try
{
Native.AppendMenu(menu, 0, new UIntPtr(101), "Copy");
Native.AppendMenu(menu, 0, new UIntPtr(102), "Rename");
Native.AppendMenu(menu, 3, new UIntPtr(103), "Unavailable");
Native.AppendMenu(menu, 0x800, UIntPtr.Zero, null);
Native.AppendMenu(submenu, 0, new UIntPtr(105), "Nested command");
Native.AppendMenu(menu, 0x10, new UIntPtr((ulong)submenu.ToInt64()), "More actions");
Native.AppendMenu(menu, 0, new UIntPtr(104), "Properties");
uint command = Native.TrackPopupMenuEx(menu, 0x100, x, y, Handle, IntPtr.Zero);
if (command != 0) Record(command, command == 101 ? "Copy" : command == 102 ? "Rename" : command == 104 ? "Properties" : "Nested command");
}
finally { Native.DestroyMenu(menu); }
return;
}
base.WndProc(ref message);
}
private void Record(uint command, string label)
{
LastCommand = command; SelectionCount++;
if (Selected != null) Selected(label);
}
protected override void Dispose(bool disposing)
{
if (disposing) accessibleMenu.Dispose(); base.Dispose(disposing);
}
}
}
+116
View File
@@ -0,0 +1,116 @@
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Microsoft.Win32;
namespace UniClik
{
internal static class Startup
{
private const string Key = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
internal static bool IsEnabled
{
get { return !String.IsNullOrWhiteSpace(ReadValue()); }
}
internal static string ReadValue() { using (RegistryKey key = Registry.CurrentUser.OpenSubKey(Key)) return key == null ? null : Convert.ToString(key.GetValue("UniClik")); }
internal static void Restore(string value)
{
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(Key))
{
if (String.IsNullOrEmpty(value)) key.DeleteValue("UniClik", false);
else key.SetValue("UniClik", value, RegistryValueKind.String);
}
}
internal static void Set(bool enabled)
{
using (RegistryKey key = Registry.CurrentUser.CreateSubKey(Key))
{
if (enabled) key.SetValue("UniClik", "\"" + Assembly.GetExecutingAssembly().Location + "\" --tray", RegistryValueKind.String);
else key.DeleteValue("UniClik", false);
}
}
}
internal static class Program
{
[STAThread] internal static void Main(string[] args)
{
bool first;
using (Mutex mutex = new Mutex(true, "Local\\UniClik." + System.Security.Principal.WindowsIdentity.GetCurrent().User.Value, out first))
{
if (!first)
{
IntPtr window = Native.FindWindow(null, "UniClik");
if (window != IntPtr.Zero) Native.PostMessage(window, (int)MainForm.ShowMessage, IntPtr.Zero, IntPtr.Zero);
return;
}
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
try { using (UniClikContext context = new UniClikContext(args.Contains("--tray"))) Application.Run(context); }
catch (Exception ex) { MessageBox.Show(ex.Message, "UniClik could not start", MessageBoxButtons.OK, MessageBoxIcon.Error); }
}
}
}
internal sealed class UniClikContext : ApplicationContext
{
private Settings settings;
private readonly MainForm form;
private readonly NotifyIcon tray;
private readonly ToolStripMenuItem enabled;
private readonly GestureEngine engine;
private bool disposed;
internal UniClikContext(bool startHidden)
{
string warning; settings = Settings.Load(out warning);
form = new MainForm(settings, Startup.IsEnabled);
IntPtr handle = form.Handle;
engine = new GestureEngine(settings, delegate(string text)
{
if (!form.IsDisposed && form.IsHandleCreated)
try { form.BeginInvoke((Action)delegate { if (!form.IsDisposed) form.ShowStatus(text); }); } catch (InvalidOperationException) { }
});
engine.RegisterPractice(form.Practice.Handle);
ContextMenuStrip menu = new ContextMenuStrip();
menu.Items.Add("Open UniClik", null, delegate { form.Reveal(); });
enabled = new ToolStripMenuItem("Enabled") { Checked = settings.Enabled }; enabled.Click += delegate { Toggle(); }; menu.Items.Add(enabled);
menu.Items.Add(new ToolStripSeparator()); menu.Items.Add("Quit UniClik", null, delegate { Quit(); });
tray = new NotifyIcon { Icon = form.Icon, Text = "UniClik - hold, hover, release", ContextMenuStrip = menu, Visible = true };
tray.DoubleClick += delegate { form.Reveal(); };
form.ToggleRequested += Toggle; form.ExitRequested += Quit;
form.ApplyRequested += delegate(Settings draft, bool startup)
{
try
{
string previousStartup = Startup.ReadValue();
bool updateStartup = Startup.IsEnabled != startup || (startup && (previousStartup ?? "").IndexOf(Assembly.GetExecutingAssembly().Location, StringComparison.OrdinalIgnoreCase) < 0);
if (updateStartup) Startup.Set(startup);
try { draft.Save(); }
catch { if (updateStartup) Startup.Restore(previousStartup); throw; }
settings = draft; engine.Update(settings); enabled.Checked = settings.Enabled;
form.Applied(settings, startup); form.ShowStatus("Settings applied. Hold " + settings.BypassKey + " while right-clicking to bypass UniClik.");
}
catch (Exception ex) { form.ShowStatus("Could not apply settings: " + ex.Message); }
};
if (warning != null) form.ShowStatus(warning);
if (!startHidden) form.Reveal();
}
private void Toggle()
{
settings.Enabled = !settings.Enabled; engine.Update(settings); enabled.Checked = settings.Enabled;
form.ReflectEnabled(settings.Enabled);
form.ShowStatus(settings.Enabled ? "UniClik resumed. Hold " + settings.BypassKey + " to bypass." : "UniClik paused. Ctrl + Alt + U resumes.");
try { settings.Save(); } catch (Exception ex) { form.ShowStatus("Pause state changed, but could not be saved: " + ex.Message); }
}
private void Quit() { form.AllowExit(); ExitThread(); }
protected override void Dispose(bool disposing)
{
if (disposing && !disposed)
{
disposed = true; engine.Dispose(); tray.Visible = false; tray.ContextMenuStrip.Dispose(); tray.Dispose(); form.AllowExit(); form.Dispose();
}
base.Dispose(disposing);
}
}
}
+78
View File
@@ -0,0 +1,78 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Script.Serialization;
namespace UniClik
{
public sealed class Settings
{
public bool Enabled { get; set; }
public bool Explorer { get; set; }
public bool Chrome { get; set; }
public bool Edge { get; set; }
public bool Firefox { get; set; }
public bool ShortHold { get; set; }
public int HoldMilliseconds { get; set; }
public int MovementPixels { get; set; }
public string BypassKey { get; set; }
public string ExcludedProcesses { get; set; }
public Settings()
{
Enabled = Explorer = Chrome = Edge = Firefox = true;
HoldMilliseconds = 180; MovementPixels = 6; BypassKey = "Alt"; ExcludedProcesses = "";
}
public Settings Clone() { return (Settings)MemberwiseClone(); }
internal void Normalize()
{
HoldMilliseconds = Math.Max(100, Math.Min(600, HoldMilliseconds));
MovementPixels = Math.Max(3, Math.Min(24, MovementPixels));
if (BypassKey != "Alt" && BypassKey != "Control" && BypassKey != "Shift") BypassKey = "Alt";
if (ExcludedProcesses == null) ExcludedProcesses = "";
}
internal int BypassVirtualKey { get { return BypassKey == "Control" ? 17 : BypassKey == "Shift" ? 16 : 18; } }
internal bool Allows(string processName, bool isPractice)
{
if (!Enabled) return false;
string name = (processName ?? "").ToLowerInvariant().Replace(".exe", "");
HashSet<string> exclusions = new HashSet<string>((ExcludedProcesses ?? "").Split(new[] { ',', ';', '\r', '\n', ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.ToLowerInvariant().Replace(".exe", "")));
if (exclusions.Contains(name)) return false;
return isPractice || (name == "explorer" && Explorer) || (name == "chrome" && Chrome) || (name == "msedge" && Edge) || (name == "firefox" && Firefox);
}
internal static string DirectoryPath { get { return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "UniClik"); } }
internal static string FilePath { get { return Path.Combine(DirectoryPath, "settings.json"); } }
internal static Settings Load(out string warning)
{
return LoadFrom(FilePath, out warning);
}
internal static Settings LoadFrom(string path, out string warning)
{
warning = null;
try
{
if (!File.Exists(path)) return new Settings();
Settings settings = new JavaScriptSerializer().Deserialize<Settings>(File.ReadAllText(path));
if (settings == null) throw new InvalidDataException("Empty settings");
settings.Normalize(); return settings;
}
catch (Exception ex) { warning = "Settings could not be read; defaults are active. " + ex.Message; return new Settings(); }
}
internal void Save()
{
SaveTo(FilePath);
}
internal void SaveTo(string path)
{
Normalize(); Directory.CreateDirectory(Path.GetDirectoryName(path));
string temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
File.WriteAllText(temporary, new JavaScriptSerializer().Serialize(this));
try
{
if (File.Exists(path)) File.Replace(temporary, path, null);
else File.Move(temporary, path);
}
finally { if (File.Exists(temporary)) File.Delete(temporary); }
}
}
}
+8
View File
@@ -0,0 +1,8 @@
param([switch]$Integration,[switch]$Diagnostic)
$ErrorActionPreference = 'Stop'
& (Join-Path $PSScriptRoot 'build.ps1') -Tests
$artifactsDirectory = Join-Path $PSScriptRoot 'artifacts'
New-Item -ItemType Directory -Path $artifactsDirectory -Force | Out-Null
$mode = if ($Diagnostic) { '--diagnostic' } elseif ($Integration) { '--integration' } else { '--unit' }
& (Join-Path $PSScriptRoot 'dist\UniClik.Tests.exe') $mode (Join-Path $artifactsDirectory 'test-results.txt')
if ($LASTEXITCODE -ne 0) { throw 'UniClik checks failed. See artifacts\test-results.txt.' }
+260
View File
@@ -0,0 +1,260 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Web.Script.Serialization;
using System.Windows.Forms;
namespace UniClik.Tests
{
internal static class Runner
{
private static readonly List<string> results = new List<string>();
private static int failures;
private static string output;
private static int nativeCycles = 20;
[STAThread] internal static int Main(string[] arguments)
{
output = arguments.Length > 1 ? arguments[1] : Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "test-results.txt");
Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false);
UnitTests();
if (arguments.Length > 0 && (arguments[0] == "--integration" || arguments[0] == "--diagnostic"))
{
if (arguments[0] == "--diagnostic") nativeCycles = 2;
using (Harness harness = new Harness()) Application.Run(harness);
}
string summary = String.Format("{0} passed, {1} failed", results.Count - failures, failures);
Console.WriteLine(summary); results.Add(summary);
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(output))); File.WriteAllLines(output, results);
return failures == 0 ? 0 : 1;
}
internal static void Check(bool condition, string description)
{
string text = (condition ? "PASS " : "FAIL ") + description;
if (!condition) failures++; results.Add(text); Console.WriteLine(text);
}
private static void UnitTests()
{
Check(Marshal.SizeOf(typeof(Native.INPUT)) == 40, "x64 SendInput structure is 40 bytes");
Check(Marshal.OffsetOf(typeof(Native.INPUT), "Data").ToInt32() == 8, "x64 input union begins at byte 8");
Check(Marshal.SizeOf(typeof(Native.MouseData)) == 32, "mouse hook structure matches Windows x64 ABI");
Check(Marshal.SizeOf(typeof(Native.MENUBARINFO)) == 48, "menu information structure matches Windows x64 ABI");
Settings settings = new Settings();
Check(settings.Allows("explorer", false) && settings.Allows("chrome", false) && settings.Allows("msedge", false) && settings.Allows("firefox", false), "default scope includes Explorer and three browsers");
Check(!settings.Allows("game", false) && !settings.Allows("notepad", false), "unlisted apps keep ordinary input");
settings.ExcludedProcesses = "CHROME.exe, firefox; explorer\r\n";
Check(!settings.Allows("chrome", false) && !settings.Allows("firefox", false) && !settings.Allows("explorer", false), "exclusions accept casing, exe suffixes and delimiters");
settings.Enabled = false; Check(!settings.Allows("msedge", false) && !settings.Allows("UniClik", true), "pause also disables the practice gesture");
settings = new Settings { HoldMilliseconds = 999, MovementPixels = -1, BypassKey = "invalid" }; settings.Normalize();
Check(settings.HoldMilliseconds == 600 && settings.MovementPixels == 3 && settings.BypassKey == "Alt", "invalid tuning is normalized");
Settings clone = settings.Clone(); clone.Enabled = false; Check(settings.Enabled, "editing a settings draft does not mutate active settings");
GestureSession gesture = new GestureSession { Opened = true, Origin = new Native.POINT(100, 100), MovementThreshold = 6 };
gesture.Move(new Native.POINT(102, 103)); Check(gesture.ActionFor(HitKind.Command) == ReleaseAction.LeaveOpen, "small click jitter cannot select a command");
gesture.Move(new Native.POINT(108, 100)); Check(gesture.ActionFor(HitKind.Command) == ReleaseAction.Select, "deliberate movement arms command selection");
gesture.Move(new Native.POINT(100, 100)); Check(gesture.Moved, "returning to the origin preserves deliberate gesture intent");
Check(gesture.ActionFor(HitKind.Submenu) == ReleaseAction.LeaveOpen, "submenu parents are not executed as leaf commands");
Check(gesture.ActionFor(HitKind.Disabled) == ReleaseAction.LeaveOpen && gesture.ActionFor(HitKind.Separator) == ReleaseAction.LeaveOpen, "disabled rows and separators never execute");
Check(gesture.ActionFor(HitKind.Unknown) == ReleaseAction.LeaveOpen, "unrecognized UI never receives a guessed click");
Check(gesture.ActionFor(HitKind.Outside) == ReleaseAction.Cancel, "release outside a confirmed menu cancels");
gesture.Cancelled = true; Check(gesture.ActionFor(HitKind.Command) == ReleaseAction.LeaveOpen, "cancelled gestures cannot commit");
Check(!GestureSession.CloseTo(new Native.POINT(Int32.MinValue, 0), new Native.POINT(Int32.MaxValue, 0), 2), "pointer-distance calculation cannot overflow");
string directory = Path.Combine(Path.GetTempPath(), "UniClik-tests-" + Guid.NewGuid().ToString("N"));
string path = Path.Combine(directory, "settings.json");
try
{
Settings saved = new Settings { ShortHold = true, HoldMilliseconds = 260, ExcludedProcesses = "firefox" }; saved.SaveTo(path);
string warning; Settings restored = Settings.LoadFrom(path, out warning);
Check(warning == null && restored.ShortHold && restored.HoldMilliseconds == 260 && restored.ExcludedProcesses == "firefox", "settings persist and reload correctly");
saved.HoldMilliseconds = 300; saved.SaveTo(path); restored = Settings.LoadFrom(path, out warning);
Check(restored.HoldMilliseconds == 300 && Directory.GetFiles(directory, "*.tmp").Length == 0, "replacing settings is atomic and leaves no temporary files");
File.WriteAllText(path, "{bad json"); restored = Settings.LoadFrom(path, out warning);
Check(warning != null && restored.HoldMilliseconds == 180 && File.ReadAllText(path) == "{bad json", "corrupt settings recover to defaults without overwriting the evidence");
}
finally { if (Directory.Exists(directory)) Directory.Delete(directory, true); }
using (MainForm form = new MainForm(new Settings(), false))
{
TextBox draft = (TextBox)typeof(MainForm).GetField("exclusions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(form);
draft.Text = "draft.exe"; form.ReflectEnabled(false);
Settings read = (Settings)typeof(MainForm).GetMethod("ReadDraft", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(form, null);
Check(read.ExcludedProcesses == "draft.exe" && !read.Enabled, "pause preserves pending form edits");
form.Applied(new Settings { ExcludedProcesses = "saved.exe", ShortHold = true }, false);
read = (Settings)typeof(MainForm).GetMethod("ReadDraft", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(form, null);
Check(read.ExcludedProcesses == "saved.exe" && read.ShortHold, "applied settings refresh the draft controls");
}
}
private sealed class Harness : Form
{
private readonly PracticeSurface practice;
private readonly Label information;
private readonly Button run = new Button();
private GestureEngine engine;
private readonly Settings config = new Settings();
private int selections, lastCommand;
private string lastStatus = "";
private Native.POINT origin;
internal Harness()
{
Text = "UniClik integration tests"; StartPosition = FormStartPosition.Manual; Location = new Point(200, 200); Size = new Size(680, 450);
practice = new PracticeSurface { Location = new Point(20, 20), Size = new Size(620, 260) }; Controls.Add(practice);
information = new Label { Location = new Point(20, 300), Size = new Size(620, 70), Text = "Testing the real hook and context menus.\nThe practice commands do not change your files or clipboard." }; Controls.Add(information);
run.Text = "Run integration checks"; run.Location = new Point(20, 375); run.Size = new Size(240, 30); Controls.Add(run);
run.Click += delegate { run.Enabled = false; run.Text = "Running checks..."; Thread worker = new Thread(delegate() { Thread.Sleep(8000); RunTests(); }) { IsBackground = true }; worker.SetApartmentState(ApartmentState.MTA); worker.Start(); };
practice.Selected += delegate { Interlocked.Increment(ref selections); Interlocked.Exchange(ref lastCommand, (int)practice.LastCommand); };
}
protected override void OnShown(EventArgs e)
{
base.OnShown(e); engine = new GestureEngine(config, delegate(string text) { lastStatus = text; }); engine.RegisterPractice(practice.Handle);
Point point = practice.PointToScreen(new Point(55, 40)); origin = new Native.POINT(point.X, point.Y);
}
private void RunTests()
{
try
{
Native.SetForegroundWindow(Handle); Thread.Sleep(150);
for (int i = 0; i < nativeCycles; i++)
{
int before = Count; StartHold(); Native.RECT item = Item(1); Move(Center(item)); Release();
Wait(delegate { return Count == before + 1; }, 1200, "selection"); Wait(delegate { return Menus().Count == 0; }, 1000, "menu closure"); Thread.Sleep(80);
Check(Count == before + 1 && Interlocked.CompareExchange(ref lastCommand, 0, 0) == 102, "native release selects Rename once, cycle " + (i + 1));
}
int actions = engine.CompletedActions;
Move(origin); SendMouse(Native.RIGHTDOWN, Native.RIGHTUP); WaitMenu(); Thread.Sleep(120);
Check(Count == nativeCycles && engine.CompletedActions == actions && Menus().Count > 0, "quick click leaves a menu open without selecting"); Dismiss();
int baseline = Count;
StartHold(); Move(Center(Item(2))); Release(); Thread.Sleep(260);
Check(Count == baseline && Menus().Count > 0, "disabled row is not selected"); Dismiss();
StartHold(); Move(Center(Item(3))); Release(); Thread.Sleep(260);
Check(Count == baseline && Menus().Count > 0, "separator is not selected"); Dismiss();
StartHold(); Move(Center(Item(4))); Release(); Thread.Sleep(260);
Check(Count == baseline && Menus().Count > 0, "submenu parent stays open on release"); Dismiss();
StartHold(); Move(Center(Item(4))); Wait(delegate { return Menus().Count >= 2; }, 1500, "submenu");
IntPtr nested = MenuContaining(1); Native.RECT nestedItem = Item(nested, 0); Move(Center(nestedItem)); Release();
Wait(delegate { return Count == baseline + 1; }, 1000, "nested command");
Check(Interlocked.CompareExchange(ref lastCommand, 0, 0) == 105, "hover navigation reaches and selects a nested command");
baseline = Count;
StartHold(); Move(new Native.POINT(origin.X - 25, origin.Y + 150)); Release(); Thread.Sleep(260);
Check(Count == baseline && Menus().Count == 0, "release outside cancels without click-through");
StartHold(); SendKey(27, false); SendKey(27, true); Thread.Sleep(80); Release(); Thread.Sleep(200);
Check(Count == baseline && Menus().Count == 0, "Escape cancels and the later right-button release cannot reopen the menu");
StartHold(); Move(Center(Item(1)));
Form other = null;
Invoke((Action)delegate { other = new Form { Text = "UniClik focus check", StartPosition = FormStartPosition.Manual, Location = new Point(950, 220), Size = new Size(300, 180) }; other.Show(); other.Activate(); });
Thread.Sleep(100); Release(); Thread.Sleep(200);
Check(Count == baseline, "changing foreground windows during a hold prevents selection");
Invoke((Action)delegate { other.Close(); other.Dispose(); Activate(); }); Dismiss();
int outsideStarts = engine.StartedGestures;
Point outsidePractice = new Point(); Invoke((Action)delegate { outsidePractice = PointToScreen(new Point(320, 340)); });
Move(new Native.POINT(outsidePractice.X, outsidePractice.Y)); SendMouse(Native.RIGHTDOWN, Native.RIGHTUP); Thread.Sleep(100);
Check(engine.StartedGestures == outsideStarts, "settings and other own-process controls retain ordinary input");
StartHold(); Native.RECT releaseItem = Item(1); Move(Center(releaseItem));
Native.POINT away = new Native.POINT(origin.X - 20, origin.Y + 180);
INPUTForReleaseAndMove(away); Thread.Sleep(260);
Check(Count == baseline, "pointer movement after release cannot cause a delayed click"); Dismiss();
int starts = engine.StartedGestures;
Move(origin); SendKey(18, false); SendMouse(Native.RIGHTDOWN); Thread.Sleep(220);
Check(engine.StartedGestures == starts && Menus().Count == 0, "bypass key preserves the original right-button press");
SendMouse(Native.RIGHTUP); SendKey(18, true); WaitMenu(); Dismiss();
config.ShortHold = true; engine.Update(config); Thread.Sleep(80);
Move(origin); SendMouse(Native.RIGHTDOWN); Thread.Sleep(50); SendMouse(Native.RIGHTUP); WaitMenu();
Check(engine.CompletedActions == actions + 1 && Count == baseline, "short-hold mode preserves a quick ordinary right-click (engine=" + engine.CompletedActions + ", expected=" + (actions + 1) + ", menu=" + Count + ", expected=" + baseline + ")"); Dismiss();
StartHold(); Move(Center(Item(0))); Release(); Wait(delegate { return Count == baseline + 1; }, 1200, "short hold selection");
Check(Interlocked.CompareExchange(ref lastCommand, 0, 0) == 101, "short-hold mode opens while held and selects on release"); baseline = Count;
Move(origin); SendMouse(Native.RIGHTDOWN); Move(new Native.POINT(origin.X + 80, origin.Y)); Thread.Sleep(260);
Check(Menus().Count == 0, "movement before the hold delay preserves right-dragging"); SendMouse(Native.RIGHTUP); Thread.Sleep(60); Dismiss();
config.ShortHold = false; engine.Update(config); Thread.Sleep(80);
StartHold(); config.Enabled = false; engine.Update(config); Thread.Sleep(80); Release(); Thread.Sleep(100);
Check(Count == baseline, "pausing during a hold prevents selection"); Dismiss();
starts = engine.StartedGestures; Move(origin); SendMouse(Native.RIGHTDOWN, Native.RIGHTUP); WaitMenu();
Check(engine.StartedGestures == starts, "paused mode passes through ordinary right-clicks"); Dismiss();
config.Enabled = true; engine.Update(config); Thread.Sleep(80);
Invoke((Action)delegate { practice.AccessibleMenu = true; });
for (int i = 0; i < 10; i++)
{
Move(origin); SendMouse(Native.RIGHTDOWN); Thread.Sleep(260);
ProbeRequest request = new ProbeRequest { ProcessId = (uint)Process.GetCurrentProcess().Id, Point = new Native.POINT(origin.X + 65, origin.Y + 15), RequestedAt = 0 };
MenuHit hit = MenuProbe.Inspect(request);
Move(request.Point); Release();
Wait(delegate { return Count == baseline + i + 1; }, 1400, "accessible selection");
Check(Count == baseline + i + 1 && engine.LastAdapter == "Accessible menu", "accessible menu release selects once, cycle " + (i + 1));
}
Check(engine.MaximumHookMilliseconds < 50, "hook callback stays below 50 ms (measured " + engine.MaximumHookMilliseconds.ToString("0.00") + " ms)");
Check(engine.CompletedActions == Count, "engine and menu agree on every committed selection (engine=" + engine.CompletedActions + ", menu=" + Count + ")");
}
catch (Exception ex) { Native.POINT pointer; Native.GetCursorPos(out pointer); Check(false, "integration exception: " + ex + "; status=" + lastStatus + "; decision=" + engine.LastPressDecision + "; foreground=" + Native.GetForegroundWindow() + "; harness=" + Handle + "; pointer=" + pointer.X + "," + pointer.Y + "; gestures=" + engine.StartedGestures + "; actions=" + engine.CompletedActions + "; buttons L/R/Alt=" + Native.GetAsyncKeyState(1) + "/" + Native.GetAsyncKeyState(2) + "/" + Native.GetAsyncKeyState(18) + "; max hook=" + engine.MaximumHookMilliseconds + "; trace=" + engine.RecentInputTrace); }
finally
{
SendMouse(Native.LEFTUP, Native.RIGHTUP); SendKey(18, true); Dismiss();
BeginInvoke((Action)delegate { Close(); });
}
}
private int Count { get { return Interlocked.CompareExchange(ref selections, 0, 0); } }
private void StartHold()
{
Native.SetForegroundWindow(Handle); Thread.Sleep(80);
Move(origin); SendMouse(Native.RIGHTDOWN); WaitMenu(); Thread.Sleep(100);
}
private static Native.POINT Center(Native.RECT rectangle) { return new Native.POINT((rectangle.Left + rectangle.Right) / 2, (rectangle.Top + rectangle.Bottom) / 2); }
private static void Wait(Func<bool> condition, int milliseconds, string description)
{
Stopwatch watch = Stopwatch.StartNew();
while (!condition()) { if (watch.ElapsedMilliseconds > milliseconds) throw new Exception("Timed out waiting for " + description); Thread.Sleep(10); }
}
private void WaitMenu() { Wait(delegate { return Menus().Count > 0; }, 1500, "menu"); }
private static List<IntPtr> Menus()
{
List<IntPtr> result = new List<IntPtr>(); uint process = (uint)Process.GetCurrentProcess().Id;
Native.EnumWindows(delegate(IntPtr hwnd, IntPtr unused) { if (Native.IsWindowVisible(hwnd) && Native.ProcessId(hwnd) == process && Native.ClassName(hwnd) == "#32768") result.Add(hwnd); return true; }, IntPtr.Zero); return result;
}
private static IntPtr MenuContaining(int count)
{
foreach (IntPtr hwnd in Menus()) { Native.MENUBARINFO menu = new Native.MENUBARINFO { Size = (uint)Marshal.SizeOf(typeof(Native.MENUBARINFO)) }; if (Native.GetMenuBarInfo(hwnd, -4, 0, ref menu) && Native.GetMenuItemCount(menu.Menu) == count) return hwnd; }
throw new Exception("Menu with " + count + " items was not found");
}
private static Native.RECT Item(IntPtr hwnd, uint index)
{
Native.MENUBARINFO menu = new Native.MENUBARINFO { Size = (uint)Marshal.SizeOf(typeof(Native.MENUBARINFO)) }; Native.RECT rectangle;
if (!Native.GetMenuBarInfo(hwnd, -4, 0, ref menu) || !Native.GetMenuItemRect(IntPtr.Zero, menu.Menu, index, out rectangle)) throw new Exception("Menu item rectangle is unavailable");
return rectangle;
}
private static Native.RECT Item(uint index) { return Item(MenuContaining(6), index); }
private static void Release() { SendMouse(Native.RIGHTUP); }
private new static void Move(Native.POINT point) { SetCursorPos(point.X, point.Y); Thread.Sleep(25); }
private static void Dismiss() { SendKey(27, false); SendKey(27, true); Thread.Sleep(100); SendKey(27, false); SendKey(27, true); Thread.Sleep(60); }
private static void SendMouse(params uint[] flags)
{
Native.INPUT[] inputs = new Native.INPUT[flags.Length];
for (int i = 0; i < flags.Length; i++) inputs[i].Data.Mouse = new Native.MOUSEINPUT { Flags = flags[i], ExtraInfo = new UIntPtr(0x55435453) };
if (Native.SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(Native.INPUT))) != inputs.Length) throw new Exception("Test input injection failed");
}
private static void SendKey(ushort key, bool up)
{
Native.INPUT[] inputs = new Native.INPUT[1]; inputs[0].Type = 1; inputs[0].Data.Keyboard = new Native.KEYBDINPUT { Key = key, Flags = up ? 2u : 0u, ExtraInfo = new UIntPtr(0x55435453) };
Native.SendInput(1, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
}
private static void INPUTForReleaseAndMove(Native.POINT point)
{
Native.INPUT[] inputs = new Native.INPUT[2]; inputs[0].Data.Mouse = new Native.MOUSEINPUT { Flags = Native.RIGHTUP, ExtraInfo = new UIntPtr(0x55435453) };
inputs[1].Data.Mouse = new Native.MOUSEINPUT { Flags = 0xC001, Dx = (int)((point.X - GetSystemMetrics(76)) * 65535L / (GetSystemMetrics(78) - 1)), Dy = (int)((point.Y - GetSystemMetrics(77)) * 65535L / (GetSystemMetrics(79) - 1)), ExtraInfo = new UIntPtr(0x55435453) };
Native.SendInput(2, inputs, Marshal.SizeOf(typeof(Native.INPUT)));
}
[DllImport("user32.dll")] private static extern bool SetCursorPos(int x, int y);
[DllImport("user32.dll")] private static extern int GetSystemMetrics(int index);
protected override void OnFormClosed(FormClosedEventArgs e) { engine.Dispose(); base.OnFormClosed(e); }
}
}
}
+9
View File
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en"><meta charset="utf-8"><title>UniClik browser menu check</title>
<style>body{font:24px system-ui;background:#101b2c;color:#e5eef7;max-width:850px;margin:80px auto}h1{color:#84f5c7}a{color:#84f5c7}p{line-height:1.6}</style>
<h1>UniClik browser menu check</h1>
<p>This local page is a controlled area for inspecting browser-provided context menus.</p>
<p>Select this harmless text to test the text menu.</p>
<p><a href="#sample">A local test link</a></p>
<p id="sample">The test link points within this page. No network connection is needed.</p>
</html>