• Win32API使用技巧 -- 置顶应用


    Win32提供了SetForegroundWindow方法可以将应用设置到前台并激活,但是在某些场景下,只调用该接口会返回0,即设置失败。比如如下场景:

    当前前台应用为一个全屏的应用,非前台应用的进程使用Process.Start()方法启动截图工具,尝试使用SetForegroundWindow()将窗口设置到前台,此时会概率性设置失败。

    尝试了多种方法后,最终使用如下方法解决了该问题:

    public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
    public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
    public const int SWP_NOSIZE = 0x1;
    public const int SWP_NOMOVE = 0x2;
    
    [DllImport("user32.dll")]
    public static extern IntPtr GetForegroundWindow();
    
    [DllImport("user32.dll")]
    public static extern bool SetForegroundWindow(IntPtr hwnd);
    
    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
    
    [DllImport("user32.dll")]
    public static extern bool SetWindowPos(IntPtr hwnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags);
    
    public void StartSnippingTool()
    {
        if (!Envronment.Is64BitProcess)
        {
            Process.Start(@"C:WindowssysnativeSnippingTool.exe");
        }
        else
        {
            Process.Start(@"C:Windowssystem32SnippingTool.exe");
        }
    
        Thread.Sleep(500);
        IntPtr snippingToolHandle = FindWindow("Microsoft-Windows-SnipperToolbar", "截图工具");
        if (snippingToolHandle != IntPtr.Zero)
        {
            SetForegroundWindowCustom(snippingToolHandle);
        }
    }
    
    private void SetForegroundWindowCustom(IntPtr hwnd)
    {
        IntPtr currentWindow = GetForegroundWindow();
        if (currentWindow == hwnd)
        {
            Console.WriteLine("应用已在顶层");
            return;
        }
    
        SetWindowPos(hwnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE);
        SetWindowPos(hwnd, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOSIZE|SWP_NOMOVE);
    
        bool result = SetForegroundWindow(hwnd);
        if (result)
        {
            Console.WriteLine("置顶应用成功");
        }
        else
        {
            Console.WriteLine("置顶应用失败");
        }
    }
    
    转载请注明出处,欢迎交流。
  • 相关阅读:
    Adobe Reader XI 自动闪退问题
    NoSQL非关系型数据库Redis (键值对(key-value)数据库) 学习笔记
    MarkdownPad2报错: Html Rendering Error (An error occurred with the Html rendering component.)
    Thymeleaf学习笔记
    Elasticsearch学习笔记2--Spring Data
    Redis5.0学习笔记
    Xshell6 评估期已过——解决办法
    Windows版抓包工具Wireshark3.0
    PHP 判断数据是否为空 ‘0’判断为空可选
    python3 多线程,多进程 ,IO多路复用
  • 原文地址:https://www.cnblogs.com/louzixl/p/14171760.html
Copyright © 2020-2023  润新知