diff --git a/src/pacs_win_uia/Interop/NativeMethods.cs b/src/pacs_win_uia/Interop/NativeMethods.cs
index af5f69e..42cb274 100644
--- a/src/pacs_win_uia/Interop/NativeMethods.cs
+++ b/src/pacs_win_uia/Interop/NativeMethods.cs
@@ -61,6 +61,7 @@ namespace pacs_win_uia.Interop
internal static extern IntPtr GetForegroundWindow();
// ---------------------------------------------------------------- screenshots (segment 2)
+ internal const uint PW_CLIENTONLY = 1;
internal const uint PW_RENDERFULLCONTENT = 2;
internal const uint SRCCOPY = 0x00CC0020;
internal const int SW_MINIMIZE = 6;
diff --git a/src/pacs_win_uia/Services/ControlLocatorService.cs b/src/pacs_win_uia/Services/ControlLocatorService.cs
index 56bb739..231ce42 100644
--- a/src/pacs_win_uia/Services/ControlLocatorService.cs
+++ b/src/pacs_win_uia/Services/ControlLocatorService.cs
@@ -21,6 +21,13 @@ namespace pacs_win_uia.Services
public IntPtr WindowHandle { get; set; }
+ ///
+ /// True when the control was found through a tolerant path (a wide window match, an inner
+ /// content window, or skipped leading path segments). The position may then be off, so the UI
+ /// says so instead of silently drawing a frame in the wrong place.
+ ///
+ public bool UsedFallback { get; set; }
+
public string Error { get; set; }
}
@@ -117,6 +124,7 @@ namespace pacs_win_uia.Services
return IntPtr.Zero;
}
+ _lastWindowMatchLevel = bestLevel;
string levelText = DescribeMatchLevel(bestLevel);
steps.Add(string.Format("匹配到顶层窗口 0x{0:X}({1} / {2},匹配级别:{3}){4}",
bestWindow.Handle.ToInt64(), bestWindow.ProcessName, bestWindow.ClassName, levelText,
@@ -132,6 +140,9 @@ namespace pacs_win_uia.Services
private const int MatchingLevels = 4;
+ /// Match level of the last FindTargetWindow call; used to flag weak matches.
+ private int _lastWindowMatchLevel;
+
///
/// 4 = process+class+title, 3 = process+class, 2 = process+title, 1 = process only.
/// Class comes before title when only one can be kept: class names are far more distinctive
@@ -198,6 +209,13 @@ namespace pacs_win_uia.Services
foreach (ControlTreeSource source in order)
{
ControlResolution resolution = TryResolveBySource(definition, windowHandle, source, steps);
+ if (resolution.Found && _lastWindowMatchLevel > 0 && _lastWindowMatchLevel <= 2)
+ {
+ // Matched by title or process alone: the located control may not be the saved one.
+ resolution.UsedFallback = true;
+ steps.Add("窗口是按较宽的规则匹配上的(级别 " + _lastWindowMatchLevel + "),定位结果需要人工核对。");
+ }
+
if (resolution.Found)
{
// The preferred source may legitimately resolve to the window itself (empty path).
@@ -368,6 +386,7 @@ namespace pacs_win_uia.Services
return new ControlResolution
{
Found = true,
+ UsedFallback = true,
ResolvedSource = ControlTreeSource.Uia,
WindowHandle = windowHandle,
Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = info }
@@ -424,6 +443,7 @@ namespace pacs_win_uia.Services
return new ControlResolution
{
Found = true,
+ UsedFallback = true,
ResolvedSource = ControlTreeSource.Uia,
WindowHandle = windowHandle,
Node = new ControlTreeNode { Source = ControlTreeSource.Uia, Uia = flexible }
diff --git a/src/pacs_win_uia/Services/ScreenshotService.cs b/src/pacs_win_uia/Services/ScreenshotService.cs
index 6a0773f..bf1e835 100644
--- a/src/pacs_win_uia/Services/ScreenshotService.cs
+++ b/src/pacs_win_uia/Services/ScreenshotService.cs
@@ -150,12 +150,19 @@ namespace pacs_win_uia.Services
result.WasRestoredTemporarily = true;
}
+ // A client-area capture asks the window to render ONLY its client area (PW_CLIENTONLY);
+ // rendering the whole window into a client-sized bitmap would be a crop, which is exactly
+ // what the operator asked not to do.
+ bool clientOnly = options.Target == ScreenshotTarget.Client;
+ uint baseFlags = NativeMethods.PW_RENDERFULLCONTENT | (clientOnly ? NativeMethods.PW_CLIENTONLY : 0);
+ uint plainFlags = clientOnly ? NativeMethods.PW_CLIENTONLY : 0;
+
try
{
- TryCaptureWith(NativeMethods.PW_RENDERFULLCONTENT, ScreenshotMethod.PrintWindowFull, handle, bounds, options, result);
+ TryCaptureWith(baseFlags, ScreenshotMethod.PrintWindowFull, handle, bounds, options, result);
if (result.Image == null)
{
- TryCaptureWith(0, ScreenshotMethod.PrintWindow, handle, bounds, options, result);
+ TryCaptureWith(plainFlags, ScreenshotMethod.PrintWindow, handle, bounds, options, result);
}
if (result.Image == null)
@@ -280,6 +287,19 @@ namespace pacs_win_uia.Services
{
Bitmap bitmap = null;
IntPtr windowDc = IntPtr.Zero;
+ int sourceX = 0;
+ int sourceY = 0;
+ if (options.Target == ScreenshotTarget.Client)
+ {
+ // The window DC's origin is the window's top-left corner, so a client capture reads
+ // from the border offset instead of cropping the frame away afterwards.
+ NativeWindowInfo info = new NativeWindowService().Capture(handle);
+ if (info != null && info.WindowBounds.IsValid && info.ClientBounds.IsValid)
+ {
+ sourceX = info.ClientBounds.Left - info.WindowBounds.Left;
+ sourceY = info.ClientBounds.Top - info.WindowBounds.Top;
+ }
+ }
IntPtr memoryDc = IntPtr.Zero;
IntPtr bitmapHandle = IntPtr.Zero;
IntPtr previous = IntPtr.Zero;
@@ -301,7 +321,7 @@ namespace pacs_win_uia.Services
}
previous = NativeMethods.SelectObject(memoryDc, bitmapHandle);
- bool ok = NativeMethods.BitBlt(memoryDc, 0, 0, bounds.Width, bounds.Height, windowDc, 0, 0, NativeMethods.SRCCOPY);
+ bool ok = NativeMethods.BitBlt(memoryDc, 0, 0, bounds.Width, bounds.Height, windowDc, sourceX, sourceY, NativeMethods.SRCCOPY);
if (!ok)
{
result.Attempts.Add("BitBlt:BitBlt 返回失败");
diff --git a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs
index eb3b220..ac9a3c9 100644
--- a/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs
+++ b/src/pacs_win_uia/UI/ControlMonitorEditorControl.cs
@@ -17,6 +17,7 @@ namespace pacs_win_uia.UI
Models.ControlTreeNode node,
Models.NativeRectangleInfo bounds,
IntPtr anchorWindow,
+ bool usedFallback,
IList steps)
{
Definition = definition;
@@ -24,8 +25,12 @@ namespace pacs_win_uia.UI
Bounds = bounds;
AnchorWindow = anchorWindow;
Steps = steps;
+ UsedFallback = usedFallback;
}
+ /// True when the control was located through a tolerant path (position may be off).
+ public bool UsedFallback { get; private set; }
+
/// Top-level window the control lives in; used to hide the frame when it goes away.
public IntPtr AnchorWindow { get; private set; }
@@ -627,7 +632,7 @@ namespace pacs_win_uia.UI
if (handler != null)
{
handler(this, new ControlLocatedEventArgs(definition, resolution.Node,
- BoundsOf(resolution.Node), resolution.WindowHandle, steps));
+ BoundsOf(resolution.Node), resolution.WindowHandle, resolution.UsedFallback, steps));
}
Report(string.Format("已定位到「{0}」({1}),焦点:{2}",
@@ -713,6 +718,13 @@ namespace pacs_win_uia.UI
return node.Window == null ? null : node.Window.WindowBounds;
}
+ /// The monitor row currently selected, for actions that need a target.
+ public ControlMonitorDefinition SelectedDefinitionForActions()
+ {
+ CommitEdits();
+ return SelectedDefinition();
+ }
+
private ControlMonitorDefinition SelectedDefinition()
{
int index = _bindingSource.Position;
diff --git a/src/pacs_win_uia/UI/MainForm.cs b/src/pacs_win_uia/UI/MainForm.cs
index 30c017d..bf6192a 100644
--- a/src/pacs_win_uia/UI/MainForm.cs
+++ b/src/pacs_win_uia/UI/MainForm.cs
@@ -76,6 +76,7 @@ namespace pacs_win_uia
private readonly HighlightOverlayForm _locateHighlight;
private readonly System.Windows.Forms.Timer _locateWatchTimer;
private ControlMonitorDefinition _locatedDefinition;
+ private ControlTreeNode _locatedNode;
private IntPtr _locatedAnchor = IntPtr.Zero;
private AppSettings _settings;
private FloatingToolbarForm _floatingToolbar;
@@ -384,10 +385,34 @@ namespace pacs_win_uia
///
private void CaptureCurrentWindow()
{
- NativeWindowInfo window = GetSelectedWindow();
+ NativeWindowInfo window = null;
+ string source = null;
+ ControlMonitorDefinition definition = _monitorEditor.SelectedDefinitionForActions();
+ if (definition != null)
+ {
+ var steps = new List();
+ string error;
+ IntPtr handle = new ControlLocatorService().FindTargetWindow(definition, steps, out error);
+ if (handle != IntPtr.Zero)
+ {
+ window = new NativeWindowService().Capture(handle);
+ source = "监控列表选中的条目「" + definition.ContentKey + "」";
+ }
+ else
+ {
+ AppLog.Warn("截图:监控条目的窗口没找到(" + error + "),改用窗口列表的选中项。");
+ }
+ }
+
if (window == null)
{
- SetStatus("请先在窗口列表里选中一个窗口,再截图。", null);
+ window = GetSelectedWindow();
+ source = "窗口列表选中的窗口";
+ }
+
+ if (window == null)
+ {
+ SetStatus("请先在监控列表里选中一个条目,或在窗口列表里选中一个窗口,再截图。", null);
return;
}
@@ -411,8 +436,8 @@ namespace pacs_win_uia
{
string path = ScreenshotService.Save(result.Image, _settings == null ? null : _settings.Screenshot.Directory,
window.ProcessName + "-" + window.HwndHex);
- SetStatus(string.Format("截图完成:方式 {0};{1}x{2};已保存 {3}{4}",
- result.Method, result.Image.Width, result.Image.Height, path,
+ SetStatus(string.Format("截图完成(目标来自{0}):方式 {1};{2}x{3};已保存 {4}{5}",
+ source, result.Method, result.Image.Width, result.Image.Height, path,
result.WasRestoredTemporarily ? "(曾临时恢复最小化窗口)" : string.Empty), null);
}
catch (Exception ex)
@@ -458,13 +483,30 @@ namespace pacs_win_uia
/// Opens the settings dialog and applies whatever was saved.
private void ShowSettings()
{
- using (var dialog = new SettingsForm(_settings, _settingsStore, _commandRunner))
+ try
{
- if (dialog.ShowDialog(this) != DialogResult.OK)
+ using (var dialog = new SettingsForm(_settings, _settingsStore, _commandRunner))
{
- return;
+ if (dialog.ShowDialog(this) != DialogResult.OK)
+ {
+ return;
+ }
}
}
+ catch (Exception ex)
+ {
+ // A dialog that fails to build must say so on screen; going quiet is how the 设置
+ // button looked broken.
+ AppLog.Error("打开设置窗口失败。", ex);
+ SetStatus("打开设置窗口失败:" + ex.Message, ex);
+ MessageBox.Show(
+ this,
+ "打开设置窗口失败:" + ex.GetType().Name + Environment.NewLine + ex.Message,
+ "设置",
+ MessageBoxButtons.OK,
+ MessageBoxIcon.Error);
+ return;
+ }
_settings = _settingsStore.Load();
_ocrContext = OcrReadContext.Create(_settings.Ocr);
@@ -777,7 +819,7 @@ namespace pacs_win_uia
// _windows is in EnumWindows (z-order) order, so the first entry is the window that is
// physically on top. When the operator clicks 刷新, the tool itself is foreground and
// excluded from the list, which is why marking only the foreground window showed nothing.
- IntPtr topmost = markColours && _windows.Count > 0 ? _windows[0].Handle : IntPtr.Zero;
+ IntPtr topmost = markColours ? FindTopmostPrimaryHandle() : IntPtr.Zero;
int shown = 0;
foreach (NativeWindowInfo window in _windows)
{
@@ -830,6 +872,33 @@ namespace pacs_win_uia
}
}
+ ///
+ /// The window that is physically on top *among the ones the list shows as primary*. Using the
+ /// very first enumerated window could mark a row inside 其他窗口, where the operator never
+ /// sees it.
+ ///
+ private IntPtr FindTopmostPrimaryHandle()
+ {
+ foreach (NativeWindowInfo window in _windows)
+ {
+ if (MatchesFilter(window, _windowSearchBox.Text.Trim()) && IsPrimaryWindow(window))
+ {
+ return window.Handle;
+ }
+ }
+
+ // No primary window passes the filter: fall back to the topmost visible one.
+ foreach (NativeWindowInfo window in _windows)
+ {
+ if (MatchesFilter(window, _windowSearchBox.Text.Trim()))
+ {
+ return window.Handle;
+ }
+ }
+
+ return IntPtr.Zero;
+ }
+
private static ListViewItem CreateWindowItem(NativeWindowInfo window)
{
var item = new ListViewItem(window.Title ?? string.Empty);
@@ -2389,18 +2458,110 @@ namespace pacs_win_uia
return;
}
- if (e.Bounds == null || !e.Bounds.IsValid)
+ string reason;
+ if (!CanShowLocateFrame(e, out reason))
{
- HideLocateFrame("已定位到控件,但该控件没有可用的屏幕矩形,无法高亮。");
+ HideLocateFrame(reason);
return;
}
_locateHighlight.ShowHighlight(e.Bounds.ToRectangle());
_locatedDefinition = e.Definition;
_locatedAnchor = e.AnchorWindow;
+ _locatedNode = e.Node;
_locateWatchTimer.Start();
SelectTreeNodeFor(e.Node);
- SetStatus("已在屏幕上高亮该控件(" + e.Bounds + ");再点一次行头可隐藏。", null);
+ SetStatus(e.UsedFallback
+ ? "已高亮该控件(" + e.Bounds + "),但这次是用容错规则定位的,框的位置可能不准:"
+ + "建议在界面里重新添加该控件;再点一次行头可隐藏。"
+ : "已在屏幕上高亮该控件(" + e.Bounds + ");再点一次行头可隐藏。", null);
+ }
+
+ ///
+ /// A frame only means something when the target window is actually on screen. Drawing one for a
+ /// hidden or minimized window puts a box in a place the operator cannot relate to anything.
+ ///
+ private static bool CanShowLocateFrame(ControlLocatedEventArgs e, out string reason)
+ {
+ reason = null;
+ if (e.Bounds == null || !e.Bounds.IsValid)
+ {
+ reason = "已定位到控件,但该控件没有可用的屏幕矩形,无法高亮。";
+ return false;
+ }
+
+ Rectangle rect = e.Bounds.ToRectangle();
+ if (rect.Width <= 1 || rect.Height <= 1)
+ {
+ reason = "控件矩形过小(" + rect + "),不画框。";
+ return false;
+ }
+
+ if (e.AnchorWindow != IntPtr.Zero)
+ {
+ if (!NativeMethods.IsWindow(e.AnchorWindow))
+ {
+ reason = "目标窗口已关闭,未画框。";
+ return false;
+ }
+
+ if (NativeMethods.IsIconic(e.AnchorWindow))
+ {
+ reason = "目标窗口已最小化:先让它显示出来再定位(画框也看不到)。";
+ return false;
+ }
+
+ if (!NativeMethods.IsWindowVisible(e.AnchorWindow))
+ {
+ reason = "目标窗口当前不可见(未显示或已隐藏),未画框。";
+ return false;
+ }
+ }
+
+ if (!SystemInformation.VirtualScreen.IntersectsWith(rect))
+ {
+ reason = "控件矩形 " + rect + " 不在可见屏幕范围内:目标窗口可能还没显示或其位置已经变了。";
+ return false;
+ }
+
+ return true;
+ }
+
+ /// Keeps the frame glued to a UIA control while the window moves or scrolls.
+ private void RefreshLocatedFrameBounds()
+ {
+ UiaElementInfo element = _locatedNode == null ? null : _locatedNode.Uia;
+ if (element == null || element.Element == null)
+ {
+ return;
+ }
+
+ try
+ {
+ System.Windows.Rect rect = element.Element.Current.BoundingRectangle;
+ if (rect.IsEmpty || double.IsInfinity(rect.Left) || double.IsInfinity(rect.Top))
+ {
+ HideLocateFrame("控件已不可见,已隐藏高亮框。");
+ return;
+ }
+
+ var bounds = new NativeRectangleInfo(
+ (int)Math.Round(rect.Left), (int)Math.Round(rect.Top),
+ (int)Math.Round(rect.Right), (int)Math.Round(rect.Bottom));
+ if (!bounds.IsValid)
+ {
+ return;
+ }
+
+ if (_locateHighlight.Bounds != bounds.ToRectangle())
+ {
+ _locateHighlight.ShowHighlight(bounds.ToRectangle());
+ }
+ }
+ catch (Exception)
+ {
+ HideLocateFrame("控件已失效,已隐藏高亮框。");
+ }
}
/// Hides the frame when the target window is gone or minimized, so nothing stale is left behind.
@@ -2426,7 +2587,10 @@ namespace pacs_win_uia
if (NativeMethods.IsIconic(_locatedAnchor))
{
HideLocateFrame("目标窗口已最小化,已隐藏高亮框。");
+ return;
}
+
+ RefreshLocatedFrameBounds();
}
private void HideLocateFrame(string reason)
@@ -2435,6 +2599,7 @@ namespace pacs_win_uia
_locateWatchTimer.Stop();
_locatedDefinition = null;
_locatedAnchor = IntPtr.Zero;
+ _locatedNode = null;
if (!string.IsNullOrEmpty(reason))
{
SetStatus(reason, null);
diff --git a/src/pacs_win_uia/UI/SettingsForm.cs b/src/pacs_win_uia/UI/SettingsForm.cs
index eeb88f2..7ef29bf 100644
--- a/src/pacs_win_uia/UI/SettingsForm.cs
+++ b/src/pacs_win_uia/UI/SettingsForm.cs
@@ -30,6 +30,7 @@ namespace pacs_win_uia.UI
private NumericUpDown _triggerInterval;
private CheckBox _triggerEnabled;
private TextBox _outputBox;
+ private SplitContainer _commandSplit;
private CheckBox _autoReadTree;
private CheckBox _highlightForeground;
@@ -107,6 +108,36 @@ namespace pacs_win_uia.UI
}
}
+ ///
+ /// SplitterDistance is validated against the panel minimums on every assignment, so the
+ /// minimums are only tightened once the container has its real size. Setting them in the
+ /// constructor threw and made the 设置 button look dead.
+ ///
+ protected override void OnLoad(EventArgs e)
+ {
+ base.OnLoad(e);
+ if (_commandSplit == null)
+ {
+ return;
+ }
+
+ try
+ {
+ int extent = _commandSplit.Width;
+ int splitter = _commandSplit.SplitterWidth;
+ int room = Math.Max(0, extent - splitter - 1);
+ int distance = Math.Max(0, Math.Min(room, (int)(extent * 0.38)));
+ _commandSplit.SplitterDistance = distance;
+ _commandSplit.Panel1MinSize = Math.Min(240, distance);
+ _commandSplit.Panel2MinSize = Math.Min(320, Math.Max(0, room - distance));
+ AppLog.Debug("设置窗口:命令区范围 " + extent + ",分隔位置 " + distance);
+ }
+ catch (Exception ex)
+ {
+ AppLog.Warn("设置窗口分隔条初始化失败。", ex);
+ }
+ }
+
/// The edited settings; only meaningful when the dialog returned OK.
public AppSettings Result
{
@@ -341,6 +372,7 @@ namespace pacs_win_uia.UI
// ---- left: execution moments; right: commands of the selected moment
var split = new SplitContainer { Dock = DockStyle.Fill, Orientation = Orientation.Vertical };
+ _commandSplit = split;
var left = new Panel { Dock = DockStyle.Fill };
var leftButtons = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 34, WrapContents = false };
@@ -380,7 +412,6 @@ namespace pacs_win_uia.UI
left.Controls.Add(triggerDetails);
left.Controls.Add(leftButtons);
split.Panel1.Controls.Add(left);
- split.Panel1MinSize = 240;
var right = new Panel { Dock = DockStyle.Fill };
var rightButtons = new FlowLayoutPanel { Dock = DockStyle.Bottom, Height = 34, WrapContents = false };
@@ -394,7 +425,6 @@ namespace pacs_win_uia.UI
right.Controls.Add(_commandGrid);
right.Controls.Add(rightButtons);
split.Panel2.Controls.Add(right);
- split.Panel2MinSize = 320;
layout.Controls.Add(split);
var actions = new FlowLayoutPanel { Dock = DockStyle.Fill, WrapContents = false };