C#:将另一个应用程序的主窗口移至屏幕最前

原创
2017/09/08 16:03
阅读数 3.6K

使用WindowsAPI函数SwitchToThisWindow,可以将指定窗口移动到屏幕最前。

如果要将另一个应用程序的窗口移动到最前,只需要找到该窗口的句柄,再调用SwitchToThisWindow函数即可。可通过遍历进程的方式找到该窗口主窗体的句柄。

建立一个C#写的Windows窗体应用程序,里面放一个TextBox用来写进程名,一个Button用来触发窗口置顶操作。

代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TopWindowTest
{
    public partial class FormMain : Form
    {
        public FormMain()
        {
            InitializeComponent();
        }

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern bool SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        /// <summary>
        /// 置顶
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnTop_Click(object sender, EventArgs e)
        {
            //找到指定的进程
            string processName = this.txtProcessName.Text;
            bool hasFound = false;
            Process processInfo = null;
            foreach (Process process in Process.GetProcesses())
            {
                if (process.ProcessName == processName)
                {
                    processInfo = process;
                    hasFound = true;
                    break;
                }
            }
            if (!hasFound)
            {
                MessageBox.Show("未找到指定进程");
                return;
            }

            //移动到最前
            SwitchToThisWindow(processInfo.MainWindowHandle, true);
        }
    }
}

程序运行结果如下,在文本框中输入calc后点击置顶按钮,计算器程序便会被移至屏幕最前:

DEMO程序下载地址:https://pan.baidu.com/s/1mimkCIG

END

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部