[C#/API] 윈도우 핸들 포커스 최상위 (FindWindow, ShowWindowAsync, SetForegroundWindow)

윈도우 제목으로 최상위 화면으로 활성화 시키는 방법


윈도우 API를 사용하여 현재 윈도우에 실행 중인 프로그램의 제목을 찾아서 해당 화면이 최상위로 오도록 만들어 보자


1. FindWindow() 함수를 사용하여 윈도우 제목으로 핸들을 찾는다

2. ShowWindowAsync() 함수를 사용하여 윈도우가 최소화 되어 있다면 다시 활성화 시킨다

3. SetForegroundWindow() 함수를 사용하여 포커스를 줘서 최상위로 오도록 만든다


윈도우 API를 사용하기 위해서는 using System.Runtime.InteropServices 꼭 선언해 줘야한다


소스파일 : WindowTitleFocus.zip


<소스코드>

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

namespace WindowTitleFocus
{
    public partial class Form1 : Form
    {
        [DllImport("user32.dll")]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow);

        private const int SW_SHOWNORMAL = 1;
        private const int SW_SHOWMINIMIZED = 2;
        private const int SW_SHOWMAXIMIZED = 3;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 윈도우 타이틀명으로 핸들을 찾는다
            IntPtr hWnd = FindWindow(null, txtTitle.Text);

            if (!hWnd.Equals(IntPtr.Zero))
            {
                // 윈도우가 최소화 되어 있다면 활성화 시킨다
                ShowWindowAsync(hWnd, SW_SHOWNORMAL);

                // 윈도우에 포커스를 줘서 최상위로 만든다
                SetForegroundWindow(hWnd);
            }
        }
    }
}



윈도우 타이틀에 프로그램의 제목을 적고 포커스 버튼을 누른다

해당 프로그램이 최상위로 오는것을 확인 할 수 있다

 

댓글

Designed by JB FACTORY