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