5 Commits
Author SHA1 Message Date
yuanyuanxianganddeepseek-flash cbb84809d8 fix(server): bind context-menu commands to the hosts the menu was opened for
The host list is a virtual list (LVS_OWNERDATA), so its selection is stored as
row indices. m_HostList is reordered underneath those indices: ApplySort() sorts
it in place on every TIMER_REFRESH_LIST tick, and RemoveFromHostList() erases
entries as hosts go offline. TrackPopupMenu runs its own modal loop, which keeps
dispatching WM_TIMER, so by the time the user clicks an item the row numbers
have already shifted. Every command handler resolves its targets at click time
with GetFirstSelectedItemPosition() + GetContextByListIndex(), a pure row lookup
(m_HostList[m_FilteredIndices[row]]), so a menu opened for host A could act on
whichever host now occupied that row.

Snapshot the selected clientIDs before the popup and restore the selection to
their current rows when it returns, dispatching the command ourselves through
TPM_RETURNCMD so the restore happens first. CMenu::TrackPopupMenu is not used
for this because its return type is BOOL, which would truncate the command ID.

Restoring the selection alone is not enough. A dozen handlers pop a confirmation
or input dialog before resolving their targets, and that modal pumps WM_TIMER
too, so the selection drifts a second time. Keep the same clientID snapshot in
m_CtxMenuTargets for the duration of the dispatch and let ResolveCommandTargets()
prefer it over re-reading the selection. Every lookup revalidates GetClientID()
against the row it landed on, so a stale index skips the host instead of acting
on a different one, and hosts that went offline while the menu was open are
dropped rather than guessed at. The snapshot is saved and restored around the
dispatch so a nested popup cannot clobber the outer one.

SendSelectedCommand, ShouldRemoteControl, SwitchSelectedProtocol, OnOnlineDelete,
OnOnlineUninstall, OnOnlineHostnote, OnOnlineRunAsAdmin, MachineManage and
ProxyClientTcpPort now resolve through it. Handlers that show no dialog before
resolving (OnMainProxy, OnOnlineAddWatch, OnOnlineInjNotepad, OnOnlineLoginNotify,
OnOnlineActiveWnd) keep reading the selection directly.

Co-Authored-By: deepseek-flash
2026-10-30 23:07:48 +01:00
yuanyuanxianganddeepseek-flash 96f1bacd43 fix(client): use GDI capture when the session has no interactive desktop
A host whose DXGI initialisation hangs never opens the remote desktop window at
all. WorkThreadProc runs InitScreenSpy() and SendBitMapInfo() back to back, so a
capturer that never finishes constructing means TOKEN_BITMAPINFO is never sent,
and the master - which only opens the window on that token - waits forever. On
the affected Server 2022 box the screen thread stopped right after logging its
type and algorithm, printing neither the DXGI init summary nor the existing
"DXGI SPY init failed" fallback, so it was stuck inside the capturer
constructor; a healthy machine on the same build reaches the summary in under a
second. Six clicks left six stuck threads, each holding a D3D device.

DXGI desktop duplication needs a display to duplicate. With no interactive
desktop it can return no frames at best, and on some drivers it never returns
from the initialisation calls at all. BitBlt has no such dependency and keeps
working, which is why switching the screen type to GDI made the same host
connect. Detect that up front and pick GDI instead of relying on a hang to be
survivable:

- IsWorkstationLocked() - the input desktop is Winlogon. Moved out of
  CKernelManager into Manager.cpp so the capturer can use it too; the manager
  keeps its private wrapper for the "Locked:"/"Inactive:" activity string.
- IsCurrentSessionDisconnected() - the process's own session is
  WTSDisconnected. That is the state the reported host was actually in: its
  client runs in session 2, which was disconnected, and the desktop only came
  back after the master's "RDP session reset" ran tscon. Session 0 has no
  disconnected state and is left alone.

Either condition means the same thing for capture, so both route to the plain
GDI capturer. An active session keeps DXGI untouched, so hosts that work today
are unaffected; the new log line names which condition fired.

Co-Authored-By: deepseek-flash
2026-10-30 22:36:01 +01:00
yuanyuanxianganddeepseek-flash 6a3d536d38 fix(server): keep the build dialog's default protocol at TCP
Commit 46f4bf2 swapped InsertString for AddString on IDC_COMBO_PROTO while
attaching protocol values as item data. That combo carries CBS_SORT, and the two
messages differ there: CB_ADDSTRING inserts in alphabetical order and returns
the sorted position, while CB_INSERTSTRING ignores CBS_SORT entirely. The list
went from TCP/UDP/HTTP/random/KCP/WebSocket/WS+TLS to HTTP/KCP/TCP/UDP/...,
so SetCurSel(0) landed on HTTP and every newly opened build dialog defaulted to
the wrong protocol.

Revert both hunks of that commit for this dialog. The items are appended with
InsertStringL like every other combo on the form, and OnBnClickedOk reads
GetCurSel() again: with no item data attached GetItemData returns 0 for every
row, so the previous guard (0 != CB_ERR) would have written TCP no matter what
the user picked. PROTO_TCP..PROTO_WSS are 0..6 without gaps and PROTO_HTTPS
sits outside the list, so the index still equals the protocol value.

Co-Authored-By: deepseek-flash
2026-10-30 22:18:17 +01:00
yuanyuanxiang 389de9d456 fix(client): fall back to GDI capture when DXGI duplication yields no frames
Some environments never deliver a frame from
IDXGIOutputDuplication::AcquireNextFrame: headless or virtual displays, Session 0
desktops, and drivers that do not push duplication notifications. It returns
DXGI_ERROR_WAIT_TIMEOUT forever, even while the desktop is changing.

Consequences:
- The first screen could not be captured, so the server kept showing
  "Please wait..." because m_bIsFirst was never cleared.
- Adding a GDI fallback for the first screen alone was not enough: the picture
  appeared but then froze, because ScanNextScreen still polled DXGI and always
  got nothing back, leaving the encoder without input.

Fixes:
- Add CaptureByGDI(), which grabs a frame with GetDC(NULL) + CreateDIBSection +
  BitBlt. GDI does not depend on desktop changes, which is why the plain GDI
  capture path always worked in these environments.
- When the first screen cannot be obtained from DXGI, capture it with GDI and
  mark the whole session as GDI (m_bGDIFallback = true), releasing the
  duplication object. All later frames then go through GDI so the picture keeps
  updating.
- Normal machines are unaffected: if DXGI delivers the probe frame or the first
  screen, the flag stays false and the GDI path is never entered. This also
  avoids mis-detecting a momentarily static desktop as a broken duplication,
  which a plain timeout counter would do.
- Create the GDI offscreen DIB lazily and reuse it (m_hGdiMemDC, m_hGdiBmp,
  m_pGdiBits). The fallback is a per-frame path, so allocating and freeing about
  15MB every frame would cause visible jitter.
- Reuse m_BitmapInfor_Full for CreateDIBSection instead of building a second
  BITMAPINFO: it is already 32bpp BI_RGB with a positive height (bottom-up) and
  matches the surface size.
- Guard the GDI buffer readiness check. If CreateCompatibleDC or SelectObject
  fails, drop the bitmap so the next call does not mistake a half-initialized
  state for a usable one; otherwise BitBlt would silently write nowhere and
  memcpy would read uninitialized memory.
- Restore the previous bitmap before DeleteDC and check for HGDI_ERROR,
  otherwise DeleteObject on the still-selected bitmap fails and leaks it.

The fallback matches the plain GDI capture path (full-size BitBlt plus
ScaleBitmap), so a downgraded session performs the same as GDI mode. The only
added cost versus DXGI is one BitBlt per frame.
2026-10-30 21:57:39 +01:00
yuanyuanxiang bc75e1ae99 fix(client): fix DXGI black screen on rotated displays and slow first frame
1. Black screen on rotated displays

Root cause: with DXGI Desktop Duplication on a rotated output,
DXGI_OUTDUPL_DESC.ModeDesc reports the logical desktop size (e.g. 1440x2560)
while the surface returned by AcquireNextFrame is the unrotated landscape
bitmap (2560x1440). The old code created cpuTexture from the ModeDesc size.
On a mismatch ID3D11DeviceContext::CopyResource returns void and silently
copies nothing, leaving the destination texture all zeros, so the first
screen and every H.264 frame were fully black (IDR was only 5KB).
The GDI path does not go through DXGI and was unaffected; the web client uses
the DIFF algorithm and was hit too, but looked different.

Fixes:
- Create cpuTexture from the real D3D11_TEXTURE2D_DESC; when the probe fails,
  derive the real surface size from Rotation instead of falling back to
  ModeDesc, which would reintroduce the black screen
- Add BlitRotated() to upright the image for ROTATE90/180/270, with a whole-row
  memcpy fast path for IDENTITY; m_ulFullWidth/Height now hold the upright
  logical size
- Treat DXGI_ERROR_WAIT_TIMEOUT as "no new frame" instead of a failure, so a
  static desktop reuses the previous frame instead of always returning nullptr
- GetFirstScreenData: fix the write offset (start at +1, previously the color
  channels were all wrong) and report the scaled size instead of the full size,
  which used to send about 8.5MB of garbage
- Validate the frame format against a whitelist; fall back to BGRA and warn for
  formats that are not 4 bytes per pixel

2. Slow first frame (the probe frame consumed the initial frame)

Root cause: the probe frame AcquireNextFrame(500), added to read the real
texture description, was released right after use and therefore discarded.
But the frame DXGI pushes after DuplicateOutput is often the only frame
available on a static desktop. After discarding it, the first-screen
AcquireNextFrame always timed out (and that timeout was 1000ms at the time),
ScreenManager had already set m_SendFirst = TRUE so it never retried, and the
encoder had no input to produce an IDR, so the picture only appeared once the
desktop changed. Symptom: MDLL/EXE builds with this fix took a long time to
show the remote desktop, while the old build without the probe frame was fast.

Fixes:
- Keep the probe frame: stash it in m_probeRes without calling ReleaseFrame and
  let the new ConsumeProbeFrame() fill the first screen once the buffers are
  allocated, so the first screen no longer depends on the desktop changing
- Probe timeout 500 -> 200ms; verify both size and format of the probe frame
  against cpuTexture and skip consumption on mismatch, otherwise a silently
  failed CopyResource would be taken as a valid all-black first screen
- CaptureFrame: drop "reuseOk ? 100 : 1000" and use a fixed 100ms timeout. The
  AcquireNextFrame timeout is an upper bound rather than a fixed wait, and
  blocking on a static desktop only slowed the capture loop down to 1Hz
- Retry the first screen up to 3 times on "no new frame" (100ms timeout plus a
  20ms gap); skip the capture entirely when the probe frame already filled it
- Release m_probeRes in CleanupDXGI and ReinitDuplication so the duplication
  object can be released

3. Incomplete picture

- Add ScreenCapture::FitDefaultSendSize(), which scales proportionally so the
  long edge stays at or below 1920 and the short edge at or below 1080, for
  both landscape and portrait. The old min(1920,w) and min(1080,h) clamped the
  axes independently and broke the aspect ratio: a 1440x2560 portrait desktop
  was squeezed to 1440x1080, keeping only 42% of the height
- Use the same helper for both the GDI and DXGI paths; common landscape
  resolutions (1920x1080, 2560x1440, 3840x2160, 1280x720) are unchanged

4. Incidental fixes

- CaptureFrame leaked desktopResource when QueryInterface failed, one DXGI
  resource per failure
- Drop the frame and warn when the surface size changes, for example after the
  user changed the resolution, so BlitRotated does not read out of bounds using
  stale sizes
2026-10-30 21:18:57 +01:00
10 changed files with 633 additions and 136 deletions

No files matched your search

+1 -11
View File
@@ -125,17 +125,7 @@ private:
bool IsWorkstationLocked() bool IsWorkstationLocked()
{ {
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ); return ::IsWorkstationLocked();
// 如果无法打开桌面,可能是因为桌面已经切换到 Winlogon
if (!hInput) return true;
char name[256] = {0};
DWORD needed;
bool isLocked = false;
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
isLocked = (_stricmp(name, "Winlogon") == 0);
}
CloseDesktop(hInput);
return isLocked;
} }
}; };
+16
View File
@@ -156,6 +156,22 @@ HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess)
return hInputDesktop; return hInputDesktop;
} }
bool IsWorkstationLocked()
{
HDESK hInput = OpenInputDesktop(0, FALSE, GENERIC_READ);
// 打不开输入桌面,通常就是已经切到 Winlogon(锁屏)
if (!hInput) return true;
char name[256] = { 0 };
DWORD needed = 0;
bool isLocked = false;
if (GetUserObjectInformationA(hInput, UOI_NAME, name, sizeof(name), &needed)) {
isLocked = (_stricmp(name, "Winlogon") == 0);
}
CloseDesktop(hInput);
return isLocked;
}
// 返回新桌面句柄,如果没有变化返回NULL // 返回新桌面句柄,如果没有变化返回NULL
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights) HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights)
{ {
+4
View File
@@ -15,6 +15,10 @@
HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess = 0); HDESK OpenActiveDesktop(ACCESS_MASK dwDesiredAccess = 0);
// 工作站是否已锁屏(输入桌面切到 Winlogon)。锁屏时 DXGI 桌面复制在部分环境会卡在
// 初始化里不返回,抓屏初始化需要据此提前走 GDI。
bool IsWorkstationLocked();
HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights); HDESK IsDesktopChanged(HDESK currentDesk, DWORD accessRights);
bool SwitchToDesktopIfChanged(HDESK& currentDesk, DWORD accessRights); bool SwitchToDesktopIfChanged(HDESK& currentDesk, DWORD accessRights);
+18
View File
@@ -866,6 +866,24 @@ public:
return bmpInfo; return bmpInfo;
} }
// 默认发送尺寸上限:等比缩放,保证长边 ≤1920、短边 ≤1080(横竖屏都成立)。
// 原实现是 min(1920,w) 与 min(1080,h) 各自独立截断,宽高比会被破坏:
// 竖屏 1440×2560 会被压成 1440×1080(高度只剩 42%)。
static void FitDefaultSendSize(LONG& w, LONG& h)
{
const LONG longEdge = (w > h) ? w : h;
const LONG shortEdge = (w > h) ? h : w;
float s = 1.0f;
if (longEdge > 1920)
s = 1920.0f / (float)longEdge;
if ((float)shortEdge * s > 1080.0f)
s = 1080.0f / (float)shortEdge;
if (s < 1.0f) {
w = (LONG)((float)w * s);
h = (LONG)((float)h * s);
}
}
// 编码器 lazy 创建。委托 EncoderFactory 完成"硬编探测 + 软编 fallback"。 // 编码器 lazy 创建。委托 EncoderFactory 完成"硬编探测 + 软编 fallback"。
void ensureEncoder(int width, int height) void ensureEncoder(int width, int height)
{ {
+382 -32
View File
@@ -24,6 +24,39 @@ private:
ID3D11Texture2D* cpuTexture = nullptr; ID3D11Texture2D* cpuTexture = nullptr;
BYTE* m_NextBuffer = nullptr; BYTE* m_NextBuffer = nullptr;
// 各缓冲是否已成功抓到过至少一帧。
// DXGI 的语义是「只在桌面有变化时才返回新帧」,静止桌面下 AcquireNextFrame
// 必然超时(DXGI_ERROR_WAIT_TIMEOUT)。超时必须复用上一帧而不是当作失败,
// 否则 ScanNextScreen 恒返回 nullptr → 只发光标帧 → H.264 编码器永远拿不到
// 首帧 IDR → 服务端 Decode() 不执行 → m_bIsFirst 无法解除 → 永久黑屏。
bool m_bFirstValid = false;
bool m_bNextValid = false;
static constexpr int kNoNewFrame = -100; // 无新帧,非错误
// 旋转输出(竖屏)下 DXGI 给的表面是「未旋转」的横向位图,
// 与桌面逻辑尺寸互为宽高交换,需要自行旋转。这里记录表面真实尺寸与旋转角。
int m_surfW = 0;
int m_surfH = 0;
DXGI_MODE_ROTATION m_rotation = DXGI_MODE_ROTATION_IDENTITY;
// InitDXGI 探测阶段抓到的帧。DuplicateOutput 之后 DXGI 会推送一帧当前桌面,
// 静止桌面下这往往就是唯一能拿到的一帧,丢弃它会导致首屏只能等桌面变化。
// 因此探测完先留在手上(不 ReleaseFrame),由 ConsumeProbeFrame() 消费。
IDXGIResource* m_probeRes = nullptr;
// DXGI 在部分环境下完全拿不到帧(无头/虚拟显示、Session 0 桌面、驱动不推送
// duplication 通知等),连首屏都要靠 GDI 兜底。这种情况下本会话直接降级为
// GDI 抓屏,否则 ScanNextScreen 永远返回 nullptr,表现为「首屏有画面,
// 但之后切换窗口画面不再更新」。
bool m_bGDIFallback = false;
// GDI 兜底用的离屏缓冲。降级后是每帧都要走的持续路径,必须复用,
// 否则每帧 CreateDIBSection/DeleteObject 会反复分配十几 MB 造成抖动。
HDC m_hGdiMemDC = nullptr;
HBITMAP m_hGdiBmp = nullptr;
HGDIOBJ m_hGdiOldBmp = nullptr;
void* m_pGdiBits = nullptr;
public: public:
ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP, BOOL all = FALSE, int level = LEVEL_H264_SOFT, ScreenCapturerDXGI(BYTE algo, int gop = DEFAULT_GOP, BOOL all = FALSE, int level = LEVEL_H264_SOFT,
RECT rc = {0}, BOOL switchScreen = TRUE) RECT rc = {0}, BOOL switchScreen = TRUE)
@@ -73,7 +106,8 @@ public:
// 4. 获取 DXGI 输出(屏幕) // 4. 获取 DXGI 输出(屏幕)
static UINT screen = 0; static UINT screen = 0;
HRESULT r = dxgiAdapter->EnumOutputs(switchScreen ? screen++ : screen, &dxgiOutput); UINT outIndex = switchScreen ? screen++ : screen;
HRESULT r = dxgiAdapter->EnumOutputs(outIndex, &dxgiOutput);
if (r == DXGI_ERROR_NOT_FOUND && all) { if (r == DXGI_ERROR_NOT_FOUND && all) {
screen = 0; screen = 0;
idx ++; idx ++;
@@ -101,16 +135,67 @@ public:
// 7. 获取屏幕大小 // 7. 获取屏幕大小
DXGI_OUTDUPL_DESC duplDesc; DXGI_OUTDUPL_DESC duplDesc;
deskDupl->GetDesc(&duplDesc); deskDupl->GetDesc(&duplDesc);
m_ulFullWidth = duplDesc.ModeDesc.Width;
m_ulFullHeight = duplDesc.ModeDesc.Height;
// 8. 创建 CPU 访问纹理 // 旋转输出(竖屏)下 ModeDesc 报告的是逻辑桌面尺寸,而实际捕获表面是
// 「未旋转」的横向位图,两者宽高互换。若按 ModeDesc 建 CPU 纹理,
// CopyResource 会静默不复制(返回 void)→ cpuTexture 全零 → 黑屏。
// 先取一帧读真实纹理描述;取不到时按旋转关系推导,避免退回错误尺寸。
m_rotation = duplDesc.Rotation;
const bool swapWH = (m_rotation == DXGI_MODE_ROTATION_ROTATE90 ||
m_rotation == DXGI_MODE_ROTATION_ROTATE270);
UINT realW = swapWH ? duplDesc.ModeDesc.Height : duplDesc.ModeDesc.Width;
UINT realH = swapWH ? duplDesc.ModeDesc.Width : duplDesc.ModeDesc.Height;
DXGI_FORMAT realFmt = DXGI_FORMAT_B8G8R8A8_UNORM;
{
IDXGIResource* probeRes = nullptr;
DXGI_OUTDUPL_FRAME_INFO probeInfo = {};
HRESULT phr = deskDupl->AcquireNextFrame(200, &probeInfo, &probeRes);
if (SUCCEEDED(phr)) {
if (probeRes) {
ID3D11Texture2D* probeTex = nullptr;
if (SUCCEEDED(probeRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&probeTex)) && probeTex) {
D3D11_TEXTURE2D_DESC td = {};
probeTex->GetDesc(&td);
realW = td.Width;
realH = td.Height;
realFmt = td.Format;
probeTex->Release();
}
// 不要丢弃这一帧:暂存起来,等缓冲分配完由 ConsumeProbeFrame()
// 直接填充首屏。否则静止桌面下首屏 AcquireNextFrame 必然超时。
m_probeRes = probeRes;
} else {
deskDupl->ReleaseFrame();
}
}
}
// 内存布局按 4 字节/像素计算,非 4 字节格式回退 BGRA
switch (realFmt) {
case DXGI_FORMAT_B8G8R8A8_UNORM:
case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB:
case DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB:
case DXGI_FORMAT_R10G10B10A2_UNORM:
break;
default:
Mprintf("[DXGI] unsupported fmt=%d, fallback BGRA\n", (int)realFmt);
realFmt = DXGI_FORMAT_B8G8R8A8_UNORM;
break;
}
// 后续所有缓冲/位图信息/缩放都按「正立」的逻辑尺寸计算
m_surfW = (int)realW;
m_surfH = (int)realH;
m_ulFullWidth = swapWH ? realH : realW;
m_ulFullHeight = swapWH ? realW : realH;
// 8. 创建 CPU 访问纹理(按表面原始尺寸/格式,保证 CopyResource 成功)
D3D11_TEXTURE2D_DESC desc = {}; D3D11_TEXTURE2D_DESC desc = {};
desc.Width = m_ulFullWidth; desc.Width = realW;
desc.Height = m_ulFullHeight; desc.Height = realH;
desc.MipLevels = 1; desc.MipLevels = 1;
desc.ArraySize = 1; desc.ArraySize = 1;
desc.Format = DXGI_FORMAT_B8G8R8A8_UNORM; desc.Format = realFmt;
desc.SampleDesc.Count = 1; desc.SampleDesc.Count = 1;
desc.Usage = D3D11_USAGE_STAGING; desc.Usage = D3D11_USAGE_STAGING;
desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ;
@@ -135,9 +220,8 @@ public:
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) * ((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
4 * m_BitmapInfor_Send->bmiHeader.biHeight; 4 * m_BitmapInfor_Send->bmiHeader.biHeight;
} else { } else {
// strategy=0 或 maxWidth=0: 默认 1080p 限制 // strategy=0 或 maxWidth=0: 默认 1080p 限制(等比,避免竖屏被压扁)
m_BitmapInfor_Send->bmiHeader.biWidth = min(1920, m_BitmapInfor_Send->bmiHeader.biWidth); FitDefaultSendSize(m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
m_BitmapInfor_Send->bmiHeader.biHeight = min(1080, m_BitmapInfor_Send->bmiHeader.biHeight);
m_BitmapInfor_Send->bmiHeader.biSizeImage = m_BitmapInfor_Send->bmiHeader.biSizeImage =
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) * ((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
4 * m_BitmapInfor_Send->bmiHeader.biHeight; 4 * m_BitmapInfor_Send->bmiHeader.biHeight;
@@ -149,6 +233,12 @@ public:
m_BmpZoomBuffer = new BYTE[m_BitmapInfor_Send->bmiHeader.biSizeImage * 2 + 12]; m_BmpZoomBuffer = new BYTE[m_BitmapInfor_Send->bmiHeader.biSizeImage * 2 + 12];
m_BmpZoomFirst = nullptr; m_BmpZoomFirst = nullptr;
// 缓冲就绪,把探测阶段暂存的那一帧直接填成首屏内容。
// 这一步让首屏不再依赖「桌面发生变化」,连接后立即可出画面。
if (m_probeRes) {
ConsumeProbeFrame();
}
// ROI // ROI
int w = m_ROI.right - m_ROI.left, h = m_ROI.bottom - m_ROI.top; int w = m_ROI.right - m_ROI.left, h = m_ROI.bottom - m_ROI.top;
if (w > 0 && h > 0) { if (w > 0 && h > 0) {
@@ -158,6 +248,11 @@ public:
m_BitmapInfor_Send->bmiHeader.biHeight = h; m_BitmapInfor_Send->bmiHeader.biHeight = h;
m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4; m_BitmapInfor_Send->bmiHeader.biSizeImage = w * h * 4;
} }
Mprintf("[DXGI] out=%u mode=%ux%u surf=%ux%u fmt=%d rot=%d -> send=%dx%d\n",
outIndex, duplDesc.ModeDesc.Width, duplDesc.ModeDesc.Height,
m_surfW, m_surfH, (int)realFmt, (int)m_rotation,
(int)m_BitmapInfor_Send->bmiHeader.biWidth,
(int)m_BitmapInfor_Send->bmiHeader.biHeight);
break; break;
} while (true); } while (true);
@@ -175,6 +270,27 @@ public:
void CleanupDXGI() void CleanupDXGI()
{ {
// GDI 兜底缓冲:先把旧位图选回 DC,再删 DC,最后删位图
if (m_hGdiMemDC) {
// SelectObject 失败会返回 HGDI_ERROR,不能拿它去恢复,否则位图仍被
// DC 选入,后面的 DeleteObject 会失败
if (m_hGdiOldBmp && m_hGdiOldBmp != HGDI_ERROR)
SelectObject(m_hGdiMemDC, m_hGdiOldBmp);
DeleteDC(m_hGdiMemDC);
m_hGdiMemDC = nullptr;
m_hGdiOldBmp = nullptr;
}
if (m_hGdiBmp) {
DeleteObject(m_hGdiBmp);
m_hGdiBmp = nullptr;
m_pGdiBits = nullptr;
}
// 探测帧若还挂着(例如 InitDXGI 中途失败),必须归还,否则 duplication 无法释放
if (m_probeRes) {
if (deskDupl) deskDupl->ReleaseFrame();
m_probeRes->Release();
m_probeRes = nullptr;
}
if (cpuTexture) cpuTexture->Release(); if (cpuTexture) cpuTexture->Release();
if (deskDupl) deskDupl->Release(); if (deskDupl) deskDupl->Release();
if (d3dContext) d3dContext->Release(); if (d3dContext) d3dContext->Release();
@@ -196,14 +312,59 @@ public:
LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength) override LPBYTE GetFirstScreenData(ULONG* ulFirstScreenLength) override
{ {
int ret = CaptureFrame(m_FirstBuffer, ulFirstScreenLength, 1); // 首屏是一次性同步操作:ScreenManager 在调用前已把 m_SendFirst 置 TRUE,
scaleBitmap(m_BmpZoomBuffer, m_FirstBuffer); // 一旦返回 nullptr 就不会再重试。所以这里尽量拿到内容——探测阶段暂存的
memcpy(m_FirstBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage); // 帧通常已填充好,静止桌面下偶尔无新帧时再用短超时补抓几次。
if (ret) const DWORD startTick = GetTickCount();
return nullptr; int ret = 0;
int attempts = 0;
if (!m_bFirstValid) { // 探测帧已填充时直接用,不再白等一次 AcquireNextFrame
ret = kNoNewFrame;
while (attempts < 3) {
++attempts;
ret = CaptureFrame(m_FirstBuffer, ulFirstScreenLength, 1, &m_bFirstValid);
if (ret != kNoNewFrame) break;
if (m_bFirstValid) { ret = 0; break; }
Sleep(20);
}
}
const DWORD elapsed = GetTickCount() - startTick;
if (elapsed > 300) {
// 只在明显偏慢时记录,正常连接不会产生这行
Mprintf("[DXGI] first screen slow: %ums attempts=%d ok=%d\n",
elapsed, attempts, ret == 0);
}
if (ret != 0) {
// DXGI 抓帧失败(无新帧 / 尺寸异常 / Map 失败等)。首屏不能放弃:一旦
// 返回 nullptr,服务端 m_bIsFirst 就再无机会解锁(ScreenManager 的
// m_SendFirst 已置 TRUE 不会重试),只能等桌面变化,表现为一直"请等待"。
if (CaptureByGDI(m_FirstBuffer, 1)) {
// duplication 连首帧都产不出来,本会话后续帧也必然是空的。
// 直接降级为 GDI 抓屏,保证画面能持续更新(否则只有首屏是活的)。
m_bGDIFallback = true;
if (deskDupl) {
deskDupl->Release();
deskDupl = nullptr;
}
Mprintf("[DXGI] no frame from duplication (ret=%d), session falls back to GDI\n", ret);
ret = 0;
} else {
*ulFirstScreenLength = 0;
return nullptr;
}
}
// reservedBytes=1,实际位图从 m_FirstBuffer+1 开始;
// 服务端也是从偏移 1 开始拷贝,写回时必须保持同样的偏移
scaleBitmap(m_BmpZoomBuffer, m_FirstBuffer + 1);
memcpy(m_FirstBuffer + 1, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
// 缓冲已被缩放图覆盖,+1 处不再是完整帧,后续无新帧时不可再复用
m_bFirstValid = false;
if (m_bAlgorithm == ALGORITHM_GRAY) { if (m_bAlgorithm == ALGORITHM_GRAY) {
ToGray(1 + m_RectBuffer, 1 + m_RectBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage); ToGray(1 + m_RectBuffer, 1 + m_RectBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
} }
// 长度必须是缩放后的发送尺寸,不能沿用 CaptureFrame 写入的全尺寸,
// 否则会把整帧原始数据(数倍于图像)一并发给服务端
*ulFirstScreenLength = m_BitmapInfor_Send->bmiHeader.biSizeImage;
m_FirstBuffer[0] = TOKEN_FIRSTSCREEN; m_FirstBuffer[0] = TOKEN_FIRSTSCREEN;
return m_FirstBuffer; return m_FirstBuffer;
} }
@@ -211,11 +372,16 @@ public:
LPBYTE ScanNextScreen() override LPBYTE ScanNextScreen() override
{ {
ULONG ulNextScreenLength = 0; ULONG ulNextScreenLength = 0;
int ret = CaptureFrame(m_NextBuffer, &ulNextScreenLength, 0); int ret = CaptureFrame(m_NextBuffer, &ulNextScreenLength, 0, &m_bNextValid);
scaleBitmap(m_BmpZoomBuffer, m_NextBuffer); if (ret == kNoNewFrame) {
memcpy(m_NextBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage); // 无新帧:m_NextBuffer 里已是上次缩放后的结果,必须原样返回,
// 不能再走一遍 scaleBitmap(源已是缩放图,重复缩放会损坏画面)
return m_bNextValid ? m_NextBuffer : nullptr;
}
if (ret) if (ret)
return nullptr; return nullptr;
scaleBitmap(m_BmpZoomBuffer, m_NextBuffer);
memcpy(m_NextBuffer, m_BmpZoomBuffer, m_BitmapInfor_Send->bmiHeader.biSizeImage);
return m_NextBuffer; return m_NextBuffer;
} }
@@ -229,6 +395,12 @@ private:
// 重新初始化 Desktop Duplication // 重新初始化 Desktop Duplication
BOOL ReinitDuplication() BOOL ReinitDuplication()
{ {
// 重建前必须把暂存帧归还,否则旧的 duplication 无法释放
if (m_probeRes) {
if (deskDupl) deskDupl->ReleaseFrame();
m_probeRes->Release();
m_probeRes = nullptr;
}
if (deskDupl) { if (deskDupl) {
deskDupl->Release(); deskDupl->Release();
deskDupl = nullptr; deskDupl = nullptr;
@@ -263,23 +435,178 @@ private:
return SUCCEEDED(hr) && deskDupl; return SUCCEEDED(hr) && deskDupl;
} }
int CaptureFrame(LPBYTE buffer, ULONG* frameSize, int reservedBytes) // 惰性创建 GDI 离屏 DIB(尺寸与 DXGI 表面一致,32bpp bottom-up,与发送格式相同)
bool EnsureGDIBuffer()
{ {
if (m_hGdiMemDC && m_hGdiBmp && m_pGdiBits) return true;
// m_BitmapInfor_Full 已是 32bpp BI_RGB、biHeight 为正(bottom-up)、
// 尺寸等于 m_ulFullWidth/Height,直接复用,不必另建一份 BITMAPINFO
if (!m_BitmapInfor_Full || m_ulFullWidth == 0 || m_ulFullHeight == 0) return false;
HDC hScreen = GetDC(NULL);
if (!hScreen) return false;
if (!m_hGdiMemDC) m_hGdiMemDC = CreateCompatibleDC(hScreen);
if (!m_hGdiBmp) {
m_hGdiBmp = CreateDIBSection(hScreen, m_BitmapInfor_Full, DIB_RGB_COLORS,
&m_pGdiBits, NULL, 0);
}
ReleaseDC(NULL, hScreen);
if (!m_hGdiMemDC || !m_hGdiBmp || !m_pGdiBits) return false;
HGDIOBJ old = SelectObject(m_hGdiMemDC, m_hGdiBmp);
if (!old || old == HGDI_ERROR) {
// 选入失败:销毁位图,否则下次会被上面的「已就绪」判断误认为可用,
// 而实际 BitBlt 写不到 m_pGdiBits,抓出来是未初始化的内存
DeleteObject(m_hGdiBmp);
m_hGdiBmp = nullptr;
m_pGdiBits = nullptr;
return false;
}
m_hGdiOldBmp = old;
return true;
}
// DXGI 的 AcquireNextFrame 只在桌面有新内容呈现时才返回。在无头/虚拟显示环境,
// 或驱动在 DuplicateOutput 后不推送初始帧时,它可能永远超时。此时首屏发不出去,
// 服务端 m_bIsFirst 永不解锁,表现为远程桌面一直停在"请等待......"。
// GDI BitBlt 不依赖桌面变化,这里用它兜底抓一帧。
bool CaptureByGDI(LPBYTE buffer, int reservedBytes)
{
if (!EnsureGDIBuffer()) return false;
HDC hScreen = GetDC(NULL);
if (!hScreen) return false;
BOOL blt = BitBlt(m_hGdiMemDC, 0, 0, (int)m_ulFullWidth, (int)m_ulFullHeight,
hScreen, m_iScreenX, m_iScreenY, SRCCOPY);
ReleaseDC(NULL, hScreen);
if (!blt) return false;
memcpy(buffer + reservedBytes, m_pGdiBits,
(size_t)m_ulFullWidth * m_ulFullHeight * 4);
return true;
}
// 把 DXGI 表面(top-down,srcW×srcH,BGRA)按 rotation 摆正后写入目标
// (bottom-up DIB,m_ulFullWidth×m_ulFullHeight)。分块处理保证缓存友好。
void BlitRotated(BYTE* dst, const BYTE* src, int srcPitch,
int srcW, int srcH, DXGI_MODE_ROTATION rot)
{
const int dstW = (int)m_ulFullWidth;
const int dstH = (int)m_ulFullHeight;
const int dstPitch = dstW * 4;
auto put = [&](int x, int y, int sx, int sy) {
memcpy(dst + (size_t)(dstH - 1 - y) * dstPitch + (size_t)x * 4,
src + (size_t)sy * srcPitch + (size_t)sx * 4, 4);
};
if (rot == DXGI_MODE_ROTATION_ROTATE90 || rot == DXGI_MODE_ROTATION_ROTATE270) {
const bool cw = (rot == DXGI_MODE_ROTATION_ROTATE90);
const int T = 32;
for (int y0 = 0; y0 < dstH; y0 += T) {
const int yEnd = (y0 + T < dstH) ? y0 + T : dstH;
for (int x0 = 0; x0 < dstW; x0 += T) {
const int xEnd = (x0 + T < dstW) ? x0 + T : dstW;
for (int y = y0; y < yEnd; y++) {
for (int x = x0; x < xEnd; x++) {
const int sx = cw ? y : (srcW - 1 - y);
const int sy = cw ? (srcH - 1 - x) : x;
put(x, y, sx, sy);
}
}
}
}
} else if (rot == DXGI_MODE_ROTATION_ROTATE180) {
for (int y = 0; y < dstH; y++)
for (int x = 0; x < dstW; x++)
put(x, y, srcW - 1 - x, srcH - 1 - y);
} else {
// IDENTITY:整行拷贝(快路径)
for (int y = 0; y < dstH; y++)
memcpy(dst + (size_t)(dstH - 1 - y) * dstPitch,
src + (size_t)y * srcPitch, (size_t)dstPitch);
}
}
// 消费 InitDXGI 探测阶段暂存的那一帧,直接填充 m_FirstBuffer(偏移 1 起)。
// 无论成败都会释放暂存资源与 DXGI 帧,避免泄漏。
bool ConsumeProbeFrame()
{
if (!m_probeRes) return false;
bool ok = false;
ID3D11Texture2D* tex = nullptr;
if (cpuTexture && m_FirstBuffer &&
SUCCEEDED(m_probeRes->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&tex)) && tex) {
// 尺寸与格式都必须与建 cpuTexture 时一致,否则 CopyResource 静默不复制
// (读出来是全零)。探测阶段 QI 失败会退回推导尺寸、格式白名单也可能把
// 非常见格式回退成 BGRA,这里再核对一次,不符就放弃消费,让
// GetFirstScreenData 走正常抓帧路径,避免把全黑画面当成首屏发出去。
D3D11_TEXTURE2D_DESC sd = {}, dd = {};
tex->GetDesc(&sd);
cpuTexture->GetDesc(&dd);
if (sd.Width == dd.Width && sd.Height == dd.Height && sd.Format == dd.Format) {
d3dContext->CopyResource(cpuTexture, tex);
D3D11_MAPPED_SUBRESOURCE mapped = {};
if (SUCCEEDED(d3dContext->Map(cpuTexture, 0, D3D11_MAP_READ, 0, &mapped))) {
BlitRotated(m_FirstBuffer + 1, (const BYTE*)mapped.pData,
(int)mapped.RowPitch, m_surfW, m_surfH, m_rotation);
d3dContext->Unmap(cpuTexture, 0);
m_bFirstValid = true;
ok = true;
}
} else {
Mprintf("[DXGI] probe %ux%u fmt=%d != cpu %ux%u fmt=%d, skip probe frame\n",
sd.Width, sd.Height, (int)sd.Format, dd.Width, dd.Height, (int)dd.Format);
}
tex->Release();
}
if (deskDupl) deskDupl->ReleaseFrame();
m_probeRes->Release();
m_probeRes = nullptr;
return ok;
}
int CaptureFrame(LPBYTE buffer, ULONG* frameSize, int reservedBytes, bool* valid)
{
// 本会话已降级为 GDI(首屏就是靠 GDI 兜底才成功的,说明 duplication 在这个
// 环境产不出帧)。继续轮询 DXGI 只会一直返回「无新帧」,画面就停住不动。
if (m_bGDIFallback) {
if (!CaptureByGDI(buffer, reservedBytes)) return -1;
*frameSize = m_ulFullWidth * m_ulFullHeight * 4;
if (valid) *valid = true;
return 0;
}
if (!deskDupl) { if (!deskDupl) {
if (!ReinitDuplication()) return -10; if (!ReinitDuplication()) return -10;
} }
// 超时保持 100ms(与修复前一致)。AcquireNextFrame 的 timeout 是「最多等
// 多久」而不是「一定等这么久」,有帧会立即返回;静止桌面下白等只会拖慢
// 抓屏线程的轮询节奏(曾用 1000ms,导致首屏和之后每一帧都阻塞 1 秒)。
const UINT timeout = 100;
// 1. 获取下一帧 // 1. 获取下一帧
IDXGIResource* desktopResource = nullptr; IDXGIResource* desktopResource = nullptr;
DXGI_OUTDUPL_FRAME_INFO frameInfo; DXGI_OUTDUPL_FRAME_INFO frameInfo;
HRESULT hr = deskDupl->AcquireNextFrame(100, &frameInfo, &desktopResource); HRESULT hr = deskDupl->AcquireNextFrame(timeout, &frameInfo, &desktopResource);
// 处理全屏切换导致的访问丢失 // 处理全屏切换导致的访问丢失
if (hr == DXGI_ERROR_ACCESS_LOST) { if (hr == DXGI_ERROR_ACCESS_LOST) {
if (ReinitDuplication()) { if (ReinitDuplication()) {
hr = deskDupl->AcquireNextFrame(100, &frameInfo, &desktopResource); hr = deskDupl->AcquireNextFrame(timeout, &frameInfo, &desktopResource);
} }
} }
// 桌面静止时没有新帧,这是 DXGI 的正常语义,不能当成错误。
// 调用方据此复用上一帧内容,保证编码器持续有输入。
if (hr == DXGI_ERROR_WAIT_TIMEOUT) {
return kNoNewFrame;
}
if (FAILED(hr)) { if (FAILED(hr)) {
return -1; return -1;
} }
@@ -289,10 +616,40 @@ private:
hr = desktopResource->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&texture); hr = desktopResource->QueryInterface(__uuidof(ID3D11Texture2D), (void**)&texture);
if (FAILED(hr)) { if (FAILED(hr)) {
deskDupl->ReleaseFrame(); deskDupl->ReleaseFrame();
desktopResource->Release(); // 原来漏了,每次失败都会泄漏一个 DXGI 资源
return -2; return -2;
} }
// 3. 复制到 CPU 纹理 // 3. 复制到 CPU 纹理
// ID3D11DeviceContext::CopyResource 返回 void:尺寸/格式不匹配时不会报错,
// 只会静默不复制(目标保持原值 = 全零)。这里显式比对描述。
// 尺寸不一致时必须放弃这一帧:BlitRotated 按 m_surfW/H 计算源偏移,
// 表面变小会越界读取(崩溃或花屏),宁可跳过等 ReinitDuplication。
{
D3D11_TEXTURE2D_DESC sd = {};
texture->GetDesc(&sd);
if ((int)sd.Width != m_surfW || (int)sd.Height != m_surfH) {
static LONG s_sizeLog = 0;
if (s_sizeLog++ < 3) {
Mprintf("[DXGI] surface changed %dx%d -> %ux%u, drop frame\n",
m_surfW, m_surfH, sd.Width, sd.Height);
}
deskDupl->ReleaseFrame();
texture->Release();
desktopResource->Release();
return -4;
}
static LONG s_fmtLog = 0;
if (s_fmtLog < 3) {
D3D11_TEXTURE2D_DESC dd = {};
cpuTexture->GetDesc(&dd);
if (sd.Format != dd.Format) {
Mprintf("[DXGI] DESC MISMATCH fmt src=%d dst=%d\n",
(int)sd.Format, (int)dd.Format);
}
s_fmtLog++;
}
}
d3dContext->CopyResource(cpuTexture, texture); d3dContext->CopyResource(cpuTexture, texture);
// 4. 释放 DXGI 资源 // 4. 释放 DXGI 资源
@@ -307,22 +664,15 @@ private:
return -3; return -3;
} }
// 6. 复制数据到缓冲区(垂直翻转) // 6. 复制数据到缓冲区(按旋转角摆正 + 垂直翻转到 bottom-up DIB)
BYTE* pData = (BYTE*)mapped.pData; BlitRotated(buffer + reservedBytes, (const BYTE*)mapped.pData,
int rowSize = m_ulFullWidth * 4; // 每行的字节数(RGBA) (int)mapped.RowPitch, m_surfW, m_surfH, m_rotation);
BYTE* dest = buffer + reservedBytes + (m_ulFullHeight - 1) * rowSize;
BYTE* src = pData;
for (int y = 0; y < m_ulFullHeight; y++) {
memcpy(dest, src, rowSize);
dest -= rowSize;
src += mapped.RowPitch;
}
// 7. 清理 // 7. 清理
d3dContext->Unmap(cpuTexture, 0); d3dContext->Unmap(cpuTexture, 0);
*frameSize = m_ulFullWidth * m_ulFullHeight * 4; *frameSize = m_ulFullWidth * m_ulFullHeight * 4;
if (valid) *valid = true;
return 0; return 0;
} }
}; };
+34 -1
View File
@@ -467,6 +467,26 @@ static BOOL RestoreConsoleSession()
return FALSE; return FALSE;
} }
// 进程所在会话是否已断开(RDP 断开后没有显示输出)。
// 这种会话里 DXGI 桌面复制拿不到帧,部分驱动上连初始化都不返回,必须走 GDI。
// Session 0 是服务会话,没有「断开」这个概念,直接返回 FALSE。
static BOOL IsCurrentSessionDisconnected()
{
DWORD sessionId = 0;
if (!ProcessIdToSessionId(GetCurrentProcessId(), &sessionId) || sessionId == 0)
return FALSE;
WTS_CONNECTSTATE_CLASS* pState = NULL;
DWORD bytes = 0;
if (!WTSQuerySessionInformationA(WTS_CURRENT_SERVER_HANDLE, sessionId, WTSConnectState,
(LPSTR*)&pState, &bytes) || !pState) {
return FALSE;
}
const BOOL disconnected = (*pState == WTSDisconnected);
WTSFreeMemory(pState);
return disconnected;
}
void CScreenManager::InitScreenSpy() void CScreenManager::InitScreenSpy()
{ {
int DXGI = USING_GDI; int DXGI = USING_GDI;
@@ -551,7 +571,20 @@ void CScreenManager::InitScreenSpy()
} }
} }
SAFE_DELETE(m_ScreenSpyObject); SAFE_DELETE(m_ScreenSpyObject);
if ((USING_DXGI == DXGI && IsWindows8orHigher())) { // 锁屏(输入桌面切到 Winlogon)或会话已断开时,当前会话没有可用的交互桌面:
// DXGI 桌面复制拿不到帧,部分环境(无 GPU 的 Server、断开/锁定的 RDP 会话)
// 甚至会在初始化里卡死不返回 —— 那样 InitScreenSpy 走不完,WorkThreadProc 里
// 紧随其后的 SendBitMapInfo() 永远发不出去,主控端一直等不到 TOKEN_BITMAPINFO,
// 连远程桌面窗口都不会弹。GDI 的 BitBlt 不依赖桌面变化,这些情况下照样能抓,
// 所以直接走 GDI。
const BOOL locked = IsWorkstationLocked();
const BOOL disconnected = IsCurrentSessionDisconnected();
const bool noDesktop = (USING_DXGI == DXGI && (locked || disconnected));
if (noDesktop) {
Mprintf("CScreenManager: no interactive desktop (locked=%d, disconnected=%d), use GDI instead of DXGI\n",
(int)locked, (int)disconnected);
}
if ((USING_DXGI == DXGI && IsWindows8orHigher() && !noDesktop)) {
m_isGDI = FALSE; m_isGDI = FALSE;
auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen); auto s = new ScreenCapturerDXGI(algo, DEFAULT_GOP, all, m_ScreenSettings.EncodeLevel, rect, switchScreen);
if (s->IsInitSucceed()) { if (s->IsInitSucceed()) {
+2 -3
View File
@@ -66,9 +66,8 @@ CScreenSpy::CScreenSpy(ULONG ulbiBitCount, BYTE algo, BOOL vDesk, int gop, BOOL
Mprintf("CScreenSpy: 自定义分辨率 %dx%d\n", Mprintf("CScreenSpy: 自定义分辨率 %dx%d\n",
m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight); m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
} else { } else {
// strategy=0 或 maxWidth=0: 默认 1080p 限制 // strategy=0 或 maxWidth=0: 默认 1080p 限制(等比,避免竖屏被压扁)
m_BitmapInfor_Send->bmiHeader.biWidth = min(1920, m_BitmapInfor_Send->bmiHeader.biWidth); FitDefaultSendSize(m_BitmapInfor_Send->bmiHeader.biWidth, m_BitmapInfor_Send->bmiHeader.biHeight);
m_BitmapInfor_Send->bmiHeader.biHeight = min(1080, m_BitmapInfor_Send->bmiHeader.biHeight);
m_BitmapInfor_Send->bmiHeader.biSizeImage = m_BitmapInfor_Send->bmiHeader.biSizeImage =
((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) * ((m_BitmapInfor_Send->bmiHeader.biWidth * m_BitmapInfor_Send->bmiHeader.biBitCount + 31) / 32) *
4 * m_BitmapInfor_Send->bmiHeader.biHeight; 4 * m_BitmapInfor_Send->bmiHeader.biHeight;
+154 -64
View File
@@ -4797,7 +4797,36 @@ void CMy2015RemoteDlg::OnNMRClickOnline(NMHDR *pNMHDR, LRESULT *pResult)
// 刷新菜单显示 // 刷新菜单显示
DrawMenuBar(); DrawMenuBar();
SubMenu->TrackPopupMenu(TPM_LEFTALIGN, Point.x, Point.y, this);
// 菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发:这期间只要有主机上下线,
// 列表就会重排(ApplySort/erase),而虚拟列表的选中项是按行号保存的,行号的含义
// 随之改变;命令处理函数又是点击那一刻才按行号解析主机。于是「对 A 主机点的菜单」
// 会落到重排后占据同一行的 B 主机上。这里先按 clientID 记住用户选中的主机,
// 菜单返回后把选中项恢复到这些主机的当前行号,最后才派发命令。
std::vector<uint64_t> selectedIds;
EnterCriticalSection(&m_cs);
POSITION selPos = m_CList_Online.GetFirstSelectedItemPosition();
while (selPos) {
int selItem = m_CList_Online.GetNextSelectedItem(selPos);
context* selCtx = GetContextByListIndex(selItem);
if (selCtx) selectedIds.push_back(selCtx->GetClientID());
}
LeaveCriticalSection(&m_cs);
// TPM_RETURNCMD:由我们自己在恢复选中项之后再派发命令。用 Win32 入口是因为
// CMenu::TrackPopupMenu 的返回值被声明成 BOOL,拿命令 ID 只能靠隐式截断。
UINT cmd = ::TrackPopupMenu(SubMenu->GetSafeHmenu(), TPM_LEFTALIGN | TPM_RETURNCMD,
Point.x, Point.y, 0, GetSafeHwnd(), nullptr);
if (cmd != 0) {
// 恢复选中项只是让界面显示与目标一致;真正的目标是下面这份 clientID 快照。
// 处理函数里往往还要先弹确认框/输入框,模态期间列表会再重排一次,所以不能让
// 处理函数回头按行号读选中项。保存外层值是为了应对嵌套弹出的菜单。
RestoreSelectionByIds(selectedIds);
std::vector<uint64_t> outer = std::move(m_CtxMenuTargets);
m_CtxMenuTargets = selectedIds;
SendMessage(WM_COMMAND, (WPARAM)cmd, 0);
m_CtxMenuTargets = std::move(outer);
}
*pResult = 0; *pResult = 0;
} }
@@ -4911,11 +4940,8 @@ VOID CMy2015RemoteDlg::SwitchSelectedProtocol(UINT nID)
// 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃。 // 选中主机的能力校验:老客户端不认识 COMMAND_SET_PROTO,收到只会丢弃。
int selected = 0, unsupported = 0; int selected = 0, unsupported = 0;
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition(); for (context* ctx : ResolveCommandTargets()) {
while (pos) { if (!ctx->IsLogin()) continue;
int item = m_CList_Online.GetNextSelectedItem(pos);
context* ctx = GetContextByListIndex(item);
if (!ctx || !ctx->IsLogin()) continue;
++selected; ++selected;
if (!ctx->SupportsProtoSwitch()) ++unsupported; if (!ctx->SupportsProtoSwitch()) ++unsupported;
} }
@@ -5218,20 +5244,17 @@ void CMy2015RemoteDlg::OnOnlineDelete()
if (IDYES != MessageBoxL(_T("确定删除选定的被控计算机吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO)) if (IDYES != MessageBoxL(_T("确定删除选定的被控计算机吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
return; return;
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
LeaveCriticalSection(&m_cs);
BYTE bToken = COMMAND_BYE; //向被控端发送一个COMMAND_SYSTEM BYTE bToken = COMMAND_BYE; //向被控端发送一个COMMAND_SYSTEM
SendSelectedCommand(&bToken, sizeof(BYTE)); //Context PreSending PostSending SendSelectedCommand(&bToken, sizeof(BYTE)); //Context PreSending PostSending
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
// 收集选中的索引(从大到小排序,避免删除时索引变化问题) for (context* ctx : targets) {
std::vector<int> selectedItems;
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
}
std::sort(selectedItems.rbegin(), selectedItems.rend());
for (int iItem : selectedItems) {
context* ctx = GetContextByListIndex(iItem);
if (!ctx) continue; if (!ctx) continue;
CString strIP = ctx->GetClientData(ONLINELIST_IP); CString strIP = ctx->GetClientData(ONLINELIST_IP);
@@ -5278,18 +5301,14 @@ VOID CMy2015RemoteDlg::OnOnlineWindowManager()
// 是否继续远程控制:如果选择多个,则继续;如果选择单个且用户锁屏无SYSTEM权限,则提示 // 是否继续远程控制:如果选择多个,则继续;如果选择单个且用户锁屏无SYSTEM权限,则提示
BOOL CMy2015RemoteDlg::ShouldRemoteControl() BOOL CMy2015RemoteDlg::ShouldRemoteControl()
{ {
context* ContextObject = nullptr;
EnterCriticalSection(&m_cs);
int count = m_CList_Online.GetSelectedCount();
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
CString activeWnd, userName; CString activeWnd, userName;
if (Pos) { int count = 0;
int iItem = m_CList_Online.GetNextSelectedItem(Pos); EnterCriticalSection(&m_cs);
ContextObject = GetContextByListIndex(iItem); std::vector<context*> targets = ResolveCommandTargets();
if (ContextObject) { count = (int)targets.size();
activeWnd = ContextObject->GetClientData(ONLINELIST_LOGINTIME); if (!targets.empty()) {
userName = ContextObject->GetAdditionalData(RES_USERNAME); activeWnd = targets[0]->GetClientData(ONLINELIST_LOGINTIME);
} userName = targets[0]->GetAdditionalData(RES_USERNAME);
} }
LeaveCriticalSection(&m_cs); LeaveCriticalSection(&m_cs);
if (count == 1 && userName != "SYSTEM" && activeWnd.Find("Locked") == 0) { if (count == 1 && userName != "SYSTEM" && activeWnd.Find("Locked") == 0) {
@@ -5498,11 +5517,7 @@ void CMy2015RemoteDlg::OnOnlineBuildClient()
VOID CMy2015RemoteDlg::SendSelectedCommand(PBYTE szBuffer, ULONG ulLength, contextModifier cb, void* user) VOID CMy2015RemoteDlg::SendSelectedCommand(PBYTE szBuffer, ULONG ulLength, contextModifier cb, void* user)
{ {
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition(); for (context* ContextObject : ResolveCommandTargets()) {
while(Pos) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
if (!ContextObject->IsLogin() && szBuffer[0] != COMMAND_BYE) if (!ContextObject->IsLogin() && szBuffer[0] != COMMAND_BYE)
continue; continue;
if (szBuffer[0] == COMMAND_UPDATE) { if (szBuffer[0] == COMMAND_UPDATE) {
@@ -7581,6 +7596,95 @@ context* CMy2015RemoteDlg::GetContextByListIndex(int iItem)
return m_HostList[realIdx]; return m_HostList[realIdx];
} }
// 按 clientID 把选中项恢复到它们当前所在的行号。
//
// 主机列表是虚拟列表(LVS_OWNERDATA),选中项按**行号**保存,而行号的含义会随
// m_HostList 重排而改变:上下线时 OnTimer 会 ApplySort() + RebuildFilteredIndices(),
// 主机下线时 RemoveFromHostList() 直接 erase,两者都会让行号整体位移。
// 右键菜单是模态的,TrackPopupMenu 期间 WM_TIMER 照常派发,所以用户在菜单里点下去
// 时,行号很可能已经指向另一台主机;命令处理函数又是点击那一刻才按行号解析主机
// (GetContextByListIndex),结果就是「对 A 主机点的菜单」落到了 B 主机上。
//
// 调用方在弹菜单前用 clientID 记住用户选中的主机,菜单返回后调用本函数把选中项搬回
// 这些主机,再派发命令,命令处理函数看到的就还是用户当初选的那批主机。
//
// 菜单打开期间下线的主机已不在列表里,无法恢复,其选中项被丢弃:处理函数会看到
// 「没选中」并给出提示,而不是误操作另一台主机——这是安全的失败方式。
void CMy2015RemoteDlg::RestoreSelectionByIds(const std::vector<uint64_t>& ids)
{
int firstRow = -1;
{
CLock lock(m_cs);
// 先清空全部选中(-1 表示作用于所有行)
m_CList_Online.SetItemState(-1, 0, LVIS_SELECTED);
for (uint64_t id : ids) {
auto it = m_ClientIndex.find(id);
if (it == m_ClientIndex.end()) continue; // 该主机已下线
const size_t hostIdx = it->second;
if (hostIdx >= m_HostList.size()) continue;
// 索引映射若因并发更新而陈旧,宁可不选,也不能选到别的主机
if (!m_HostList[hostIdx] || m_HostList[hostIdx]->GetClientID() != id) continue;
// 在过滤索引里找它的当前显示行
int row = -1;
for (size_t fi = 0; fi < m_FilteredIndices.size(); ++fi) {
if (m_FilteredIndices[fi] == hostIdx) {
row = (int)fi;
break;
}
}
if (row < 0) continue; // 被当前分组过滤排除
m_CList_Online.SetItemState(row, LVIS_SELECTED, LVIS_SELECTED);
if (firstRow < 0) firstRow = row;
}
}
// 滚动和重绘会同步触发绘制,放到锁外,不占着主机列表锁
if (firstRow >= 0) {
m_CList_Online.SetItemState(firstRow, LVIS_FOCUSED, LVIS_FOCUSED);
m_CList_Online.EnsureVisible(firstRow, FALSE);
}
// 重排期间列表用了 LVSICF_NOINVALIDATEALL,可见行可能还是旧内容,补一次重绘
m_CList_Online.Invalidate(FALSE);
}
// 取本次命令要作用的主机。
//
// 平时就是列表里的选中项;右键菜单派发期间 m_CtxMenuTargets 非空,此时以快照为准。
// 原因:菜单点击到命令真正执行之间还夹着 MessageBoxL / DoModal 等模态框,模态循环里
// WM_TIMER 照常派发,列表会 ApplySort/erase 重排,此时再按行号读选中项就会读到另一台
// 主机。快照按 clientID 保存,与行号无关。
//
// 调用方需持有 m_cs(本函数内部不加锁)。
std::vector<context*> CMy2015RemoteDlg::ResolveCommandTargets()
{
std::vector<context*> targets;
if (!m_CtxMenuTargets.empty()) {
targets.reserve(m_CtxMenuTargets.size());
for (uint64_t id : m_CtxMenuTargets) {
auto it = m_ClientIndex.find(id);
if (it == m_ClientIndex.end()) continue; // 菜单打开期间已下线
const size_t hostIdx = it->second;
if (hostIdx >= m_HostList.size()) continue;
context* ctx = m_HostList[hostIdx];
// 索引映射若因并发更新而陈旧,宁可不操作,也不能操作到别的主机
if (!ctx || ctx->GetClientID() != id) continue;
targets.push_back(ctx);
}
return targets;
}
POSITION pos = m_CList_Online.GetFirstSelectedItemPosition();
while (pos) {
context* ctx = GetContextByListIndex(m_CList_Online.GetNextSelectedItem(pos));
if (ctx) targets.push_back(ctx);
}
return targets;
}
// 从 m_HostList 中移除 context 并更新索引映射。 // 从 m_HostList 中移除 context 并更新索引映射。
// //
// 重要:MarkDeviceOffline / m_ActiveWndW.erase 等"主机下线"副作用必须**只在 // 重要:MarkDeviceOffline / m_ActiveWndW.erase 等"主机下线"副作用必须**只在
@@ -8822,16 +8926,15 @@ void CMy2015RemoteDlg::OnOnlineHostnote()
BOOL modified = FALSE; BOOL modified = FALSE;
uint64_t key = 0; uint64_t key = 0;
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition(); // 输入框是模态的,期间列表可能已重排,目标按 clientID 还原,避免备注写到别的主机
while (Pos) { for (context* ContextObject : ResolveCommandTargets()) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
m_ClientMap->SetClientMapData(ContextObject->GetClientID(), MAP_NOTE, dlg.m_str); m_ClientMap->SetClientMapData(ContextObject->GetClientID(), MAP_NOTE, dlg.m_str);
// 虚拟列表:刷新该行以显示新备注
m_CList_Online.RedrawItems(iItem, iItem);
modified = TRUE; modified = TRUE;
} }
if (modified) {
// 虚拟列表:整表重绘,让新备注显示出来
m_CList_Online.Invalidate(FALSE);
}
LeaveCriticalSection(&m_cs); LeaveCriticalSection(&m_cs);
if (modified) { if (modified) {
m_ClientMap->SaveToFile(GetDbPath()); m_ClientMap->SaveToFile(GetDbPath());
@@ -11525,11 +11628,8 @@ void CMy2015RemoteDlg::OnOnlineRunAsAdmin()
if (MessageBoxL("确定要以管理员权限重新启动目标应用程序吗?\n此操作可能触发 UAC 账户控制。", if (MessageBoxL("确定要以管理员权限重新启动目标应用程序吗?\n此操作可能触发 UAC 账户控制。",
"提示", MB_ICONQUESTION | MB_YESNO) == IDYES) { "提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition(); // 确认框期间列表可能已重排,目标按 clientID 还原
while (Pos) { for (context* ContextObject : ResolveCommandTargets()) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
BYTE token = CMD_RUNASADMIN; BYTE token = CMD_RUNASADMIN;
ContextObject->Send2Client(&token, sizeof(token)); ContextObject->Send2Client(&token, sizeof(token));
} }
@@ -11573,20 +11673,17 @@ void CMy2015RemoteDlg::OnOnlineUninstall()
if (IDYES != MessageBoxL(_T("确定卸载选定的被控程序吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO)) if (IDYES != MessageBoxL(_T("确定卸载选定的被控程序吗?"), _T("提示"), MB_ICONQUESTION | MB_YESNO))
return; return;
// 确认框是模态的,期间列表可能已经重排;目标在锁内一次性锁定,后面发指令和
// 移除列表两步都用这份结果,避免两处按行号各自解析出不同的主机。
EnterCriticalSection(&m_cs);
std::vector<context*> targets = ResolveCommandTargets();
LeaveCriticalSection(&m_cs);
BYTE bToken = TOKEN_UNINSTALL; BYTE bToken = TOKEN_UNINSTALL;
SendSelectedCommand(&bToken, sizeof(BYTE)); SendSelectedCommand(&bToken, sizeof(BYTE));
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
// 收集选中的索引(从大到小排序,避免删除时索引变化问题) for (context* ctx : targets) {
std::vector<int> selectedItems;
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
while (Pos) {
selectedItems.push_back(m_CList_Online.GetNextSelectedItem(Pos));
}
std::sort(selectedItems.rbegin(), selectedItems.rend());
for (int iItem : selectedItems) {
context* ctx = GetContextByListIndex(iItem);
if (!ctx) continue; if (!ctx) continue;
CString strIP = ctx->GetClientData(ONLINELIST_IP); CString strIP = ctx->GetClientData(ONLINELIST_IP);
@@ -11771,11 +11868,8 @@ void CMy2015RemoteDlg::MachineManage(MachineCommand type)
{ {
if (MessageBoxL("此操作需客户端具有管理员权限,确定继续吗? ", "提示", MB_ICONQUESTION | MB_YESNO) == IDYES) { if (MessageBoxL("此操作需客户端具有管理员权限,确定继续吗? ", "提示", MB_ICONQUESTION | MB_YESNO) == IDYES) {
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition(); // 确认框期间列表可能已重排,目标由 ResolveCommandTargets 按 clientID 还原
while (Pos) { for (context* ContextObject : ResolveCommandTargets()) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ContextObject = GetContextByListIndex(iItem);
if (!ContextObject) continue;
BYTE token[32] = { TOKEN_MACHINE_MANAGE, type }; BYTE token[32] = { TOKEN_MACHINE_MANAGE, type };
ContextObject->Send2Client(token, sizeof(token)); ContextObject->Send2Client(token, sizeof(token));
} }
@@ -12847,13 +12941,9 @@ void CMy2015RemoteDlg::ProxyClientTcpPort(bool isStandard, bool autoRun)
info->Schedule.Mode = autoRun ? SCH_MODE_STARTUP : SCH_MODE_NONE; info->Schedule.Mode = autoRun ? SCH_MODE_STARTUP : SCH_MODE_NONE;
FrpcParam param(key.c_str(), timestamp, ip.c_str(), serverPort, localPort, remotePort); FrpcParam param(key.c_str(), timestamp, ip.c_str(), serverPort, localPort, remotePort);
EnterCriticalSection(&m_cs); EnterCriticalSection(&m_cs);
POSITION Pos = m_CList_Online.GetFirstSelectedItemPosition();
BOOL sent = FALSE; BOOL sent = FALSE;
const char* validDate = isStandard ? "Jan 29 2026" : "Dec 22 2025"; const char* validDate = isStandard ? "Jan 29 2026" : "Dec 22 2025";
while (Pos) { for (context* ctx : ResolveCommandTargets()) {
int iItem = m_CList_Online.GetNextSelectedItem(Pos);
context* ctx = GetContextByListIndex(iItem);
if (!ctx) continue;
if (!ctx->IsLogin()) if (!ctx->IsLogin())
continue; continue;
CString bits = ctx->GetAdditionalData(RES_PROGRAM_BITS); CString bits = ctx->GetAdditionalData(RES_PROGRAM_BITS);
+10
View File
@@ -412,6 +412,16 @@ public:
std::string m_v2KeyPath; // V2 密钥文件路径 std::string m_v2KeyPath; // V2 密钥文件路径
void RebuildFilteredIndices(); // 重建过滤索引 void RebuildFilteredIndices(); // 重建过滤索引
context* GetContextByListIndex(int iItem); // 根据列表索引获取 context(考虑分组过滤) context* GetContextByListIndex(int iItem); // 根据列表索引获取 context(考虑分组过滤)
// 按 clientID 把选中项恢复到它们当前所在的行号。虚拟列表的选中项是按行号保存的,
// 而 m_HostList 会随主机上下线重排,同一个行号重排后往往指向另一台主机。
void RestoreSelectionByIds(const std::vector<uint64_t>& ids);
// 本次命令的目标主机:右键菜单派发期间(m_CtxMenuTargets 非空)以 clientID 快照为准,
// 否则取列表当前选中项。调用方需持有 m_cs。
std::vector<context*> ResolveCommandTargets();
// 右键菜单发起时锁定的目标主机(clientID 快照)。菜单弹出到命令真正执行之间还会插入
// MessageBoxL / DoModal 等模态框,模态循环里 WM_TIMER 照常派发、列表照常重排,命令
// 处理函数若在那之后再按行号读选中项,就会读到另一台主机。只在 UI 线程访问。
std::vector<uint64_t> m_CtxMenuTargets;
// 启发式 ID 迁移:新客户端首次上线时,按 (ComputerName, ProgramPath) 在 m_ClientMap // 启发式 ID 迁移:新客户端首次上线时,按 (ComputerName, ProgramPath) 在 m_ClientMap
// 里找老条目,若唯一匹配则把元数据(备注/位置/级别/授权)拷贝到 newId。 // 里找老条目,若唯一匹配则把元数据(备注/位置/级别/授权)拷贝到 newId。
+12 -25
View File
@@ -542,14 +542,7 @@ void CBuildDlg::OnBnClickedOk()
g_ConnectAddress.SetAdminId(GetMasterHash().c_str()); g_ConnectAddress.SetAdminId(GetMasterHash().c_str());
g_ConnectAddress.SetServer(m_strIP, atoi(m_strPort)); g_ConnectAddress.SetServer(m_strIP, atoi(m_strPort));
g_ConnectAddress.runningType = m_ComboRunType.GetCurSel(); g_ConnectAddress.runningType = m_ComboRunType.GetCurSel();
// 协议值取自 item data(见 OnInitDialog 里的 addProto)。取不到时退回序号,保持旧行为。 g_ConnectAddress.protoType = m_ComboProto.GetCurSel();
int protoSel = m_ComboProto.GetCurSel();
if (protoSel >= 0) {
DWORD_PTR protoData = m_ComboProto.GetItemData(protoSel);
if (protoData != (DWORD_PTR)CB_ERR)
protoSel = (int)protoData;
}
g_ConnectAddress.protoType = protoSel;
g_ConnectAddress.iHeaderEnc = m_ComboEncrypt.GetCurSel(); g_ConnectAddress.iHeaderEnc = m_ComboEncrypt.GetCurSel();
memcpy(g_ConnectAddress.pwdHash, GetPwdHash().c_str(), sizeof(g_ConnectAddress.pwdHash)); memcpy(g_ConnectAddress.pwdHash, GetPwdHash().c_str(), sizeof(g_ConnectAddress.pwdHash));
memcpy(g_ConnectAddress.szGroupName, m_sGroupName, m_sGroupName.GetLength()); memcpy(g_ConnectAddress.szGroupName, m_sGroupName, m_sGroupName.GetLength());
@@ -844,23 +837,17 @@ BOOL CBuildDlg::OnInitDialog()
m_ComboRunType.InsertStringL(RUNNING_PARALLEL, "并发上线"); m_ComboRunType.InsertStringL(RUNNING_PARALLEL, "并发上线");
m_ComboRunType.SetCurSel(RUNNING_RANDOM); m_ComboRunType.SetCurSel(RUNNING_RANDOM);
// 协议值挂在 item data 上,不再依赖「下拉框序号 == protoType」。两者目前确实相等, m_ComboProto.InsertStringL(PROTO_TCP, "TCP");
// 但只要以后有 PROTO_* 常量没进这个下拉框(PROTO_HTTPS 就已经是这种情况), m_ComboProto.InsertStringL(PROTO_UDP, "UDP");
// 后加项序号与协议值就会错位,而错误的值只会在客户端连不上时才暴露。 m_ComboProto.InsertStringL(PROTO_HTTP, "HTTP");
auto addProto = [this](int proto, LPCSTR text) { m_ComboProto.InsertStringL(PROTO_RANDOM, "随机");
// AddString 追加到末尾并返回新条目下标;用它定位,不依赖任何「下标 == 枚举值」约定。 m_ComboProto.InsertStringL(PROTO_KCP, "KCP");
int idx = m_ComboProto.AddStringL(text); // 序号即 protoType,中间不能有空洞(下方 GetCurSel 直接当协议值用)。
if (idx >= 0) // 该下拉框资源带 CBS_SORT 样式:InsertString 不受它影响,能保持这里的顺序,
m_ComboProto.SetItemData(idx, (DWORD_PTR)proto); // 换成 AddString 会按字母序重排,HTTP 抢到第 0 项,默认协议就错了。
}; m_ComboProto.InsertStringL(PROTO_WS, "WebSocket");
addProto(PROTO_TCP, "TCP"); m_ComboProto.InsertStringL(PROTO_WSS, "WS+TLS");
addProto(PROTO_UDP, "UDP"); m_ComboProto.SetCurSel(PROTO_TCP);
addProto(PROTO_HTTP, "HTTP");
addProto(PROTO_RANDOM, "随机");
addProto(PROTO_KCP, "KCP");
addProto(PROTO_WS, "WebSocket");
addProto(PROTO_WSS, "WS+TLS");
m_ComboProto.SetCurSel(0);
m_ComboEncrypt.InsertStringL(PROTOCOL_SHINE, "Shine"); m_ComboEncrypt.InsertStringL(PROTOCOL_SHINE, "Shine");
m_ComboEncrypt.InsertStringL(PROTOCOL_HELL, "HELL"); m_ComboEncrypt.InsertStringL(PROTOCOL_HELL, "HELL");