找到在任务管理器中右键单击并选择“置于最前面”时使用的代码

逆向工程 视窗 登录
2021-07-08 06:55:23

当您在 Windows 任务管理器中右键单击某个进程并单击“置于前端”时,如何找出正在调用的代码?

这与https://stackoverflow.com/questions/45046765/bring-window-to-foreground-when-mainwindowhandle-is-0有关

SetForegroundWindow方法仅在MainWindowHandle不为 0时才有效。但即使MainWindowHandle为 0 ,Windows 任务管理器中的“置于前端”按钮也有效

1个回答

这是答案:http : //reinventingthewheel.azurewebsites.net/MainWindowHandleIsALie.aspx

我不得不使用EnumWindows以获得正确的句柄。

$TypeDef2 = @"

    using System;
    using System.Text;
    using System.Collections.Generic;
    using System.Runtime.InteropServices;

    namespace Api
    {

    public class WinStruct
    {
       public string WinTitle {get; set; }
       public int MainWindowHandle { get; set; }
    }

    public class ApiDef
    {
       private delegate bool CallBackPtr(int hwnd, int lParam);
       private static CallBackPtr callBackPtr = Callback;
       private static List<WinStruct> _WinStructList = new List<WinStruct>();

       [DllImport("User32.dll")]
       [return: MarshalAs(UnmanagedType.Bool)]
       private static extern bool EnumWindows(CallBackPtr lpEnumFunc, IntPtr lParam);

       [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
       static extern int GetWindowText(IntPtr hWnd, StringBuilder lpString, int nMaxCount);

       private static bool Callback(int hWnd, int lparam)
       {
           StringBuilder sb = new StringBuilder(256);
           int res = GetWindowText((IntPtr)hWnd, sb, 256);
          _WinStructList.Add(new WinStruct { MainWindowHandle = hWnd, WinTitle = sb.ToString() });
           return true;
       }  

       public static List<WinStruct> GetWindows()
       {
          _WinStructList = new List<WinStruct>();
          EnumWindows(callBackPtr, IntPtr.Zero);
          return _WinStructList;
       }

    }
    }
    "@

    Add-Type -TypeDefinition $TypeDef2 -Language CSharpVersion3

    $excelInstance = [Api.Apidef]::GetWindows() | Where-Object { $_.WinTitle.ToUpper() -eq "Microsoft Excel - Compatibility Checker".ToUpper() }

$TypeDef1 = @"
      using System;
      using System.Runtime.InteropServices;
      public class Tricks {
         [DllImport("user32.dll")]
         [return: MarshalAs(UnmanagedType.Bool)]
         public static extern bool SetForegroundWindow(IntPtr hWnd);
      }
    "@

    Add-Type -TypeDefinition $TypeDef1 -Language CSharpVersion3

    [void][Tricks]::SetForegroundWindow($excelInstance.MainWindowHandle)