Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)

C# - 다른 윈도우 프로그램이 실행되었음을 인식하는 방법

아래와 같은 질문이 있군요. ^^

다른 프로세스 실행 후 포커스 가져오기
; https://www.sysnet.pe.kr/3/0/5820

물론, 가장 좋은 방법은 다른 프로세스에서 준비가 되었을 때 특정 signal을 set하는 것입니다. 하지만, 그게 안 된다면 어떻게든 다른 방법을 찾아야 합니다. 예제와 함께 ^^ 설명해 볼까요?

우선, WinForm #1 응용 프로그램을 다음과 같이 만듭니다.

using System.Diagnostics;
using System.Runtime.InteropServices;

namespace WinFormsApp1
{
    public partial class Form1 : Form
    {
        // Why does my program successfully take foreground only when running under the debugger?
        // Foreground activation permission is like love: You can’t steal it, it has to be given to you
        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd); 

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
            t.Interval = 1000;
            t.Tick += (s, ev) =>
            {
                t.Stop();
                
                Process p = Process.Start("WinFormsApp2.exe");

                Thread.Sleep(1000);
                SetForegroundWindow(this.Handle); 
            };
            t.Start();
        }
    }
}

하는 일은 WinFormsApp2.exe를 실행 후, 1초 대기한 다음 자신의 윈도우를 상위에 위치시키는 SetForegroundWindow를 호출하고 있습니다. 그다음 WinFormsApp2.exe를 기본 Windows Forms 프로젝트로 만든 후, 위의 프로그램을 실행하면 의도한 대로 실행이 됩니다.

1. WinFormsApp1.exe 실행
2. 1초 후, 자동으로 WinFormsApp2.exe 실행
3. 1초 후, WinFormsApp1을 SetForegroundWindow로 지정

그런데, 여기서 문제가 있습니다. 바로 WinFormsApp2.exe로부터 포커스를 뺏어올 대기 시간을 1초로 지정한 것인데요, 이것이 왜 문제가 되는지 재현을 위해 WinFormsApp2.exe의 Program.cs에 다음과 같은 코드를 추가합니다.

namespace WinFormsApp2
{
    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            Thread.Sleep(2000);

            // ApplicationConfiguration.Initialize();
            Application.Run(new Form1());
        }
    }
}

이제 다시 실행해 보면 당연히 WinFormsApp1.exe는 입력 포커스를 가져가지 못합니다. 왜냐하면, 1초 후 #1 응용 프로그램은 SetForegroundWindow를 호출했고, 다시 1초의 시간이 지나서 그제야 #2 응용 프로그램이 화면에 떴기 때문입니다.




Windows는 이런 경우에 한해 사용할 수 있는 옵션을 하나 제공하고 있습니다.

WaitForInputIdle function (winuser.h)
; https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-waitforinputidle

Waits until the specified process has finished processing its initial input and is waiting for user input with no input pending, or until the time-out interval has elapsed.


위의 조건을 만족하려면 대상 프로그램은 메시지 큐를 가지고 있어야 합니다. 즉, 그 메시지 큐를 이용해 입력을 처리할 준비가 될 때까지 대기한다는 건데요, 닷넷(C#)에서는 Process.WaitForInputIdle 메서드를 이용해 동일한 기능을 실행할 수 있습니다.

예제와 같은 상황에서는, #1에서 #2 프로그램을 실행할 때 WaitForInputIdle을 실행하는 것입니다.

t.Tick += (s, ev) =>
{
    t.Stop();
                
    Process p = Process.Start("WinFormsApp2.exe");
    p.WaitForInputIdle();

    Thread.Sleep(1000);
    SetForegroundWindow(this.Handle); 
};

그럼 다시 정상적으로 입력 포커스를 가져오는 것을 확인할 수 있습니다.




하지만, WaitForInputIdle 역시 문제가 있습니다. 우선, 대상 프로그램이 메시지 루프를 가져야 하기 때문에 콘솔 프로그램에는 쓸 수 없습니다. 달리 말하면, 해당 응용 프로그램에 메시지 큐가 생성되면, 즉, 메시지 루프를 시작하는 GetMessage가 호출되는 순간 WaitForInputIdle은 조건을 만족하기 때문에 대기를 끝냅니다.

따라서, 메시지 루프가 생성된 후, 어떤 식으로든 #2 응용 프로그램의 윈도우가 늦게 뜬다면 SetForegroundWindow는 그 역할을 하지 못합니다. 이에 대한 테스트도 역시 간단하게, #2 응용 프로그램의 Form Load 이벤트에 Sleep을 추가해 확인할 수 있습니다.

private void Form1_Load(object sender, EventArgs e)
{
    Thread.Sleep(1000 * 3);
}

그러면 우리는 ^^ 다시, 이에 대한 예방책으로 #2의 Main Window가 떴다는 것을 한 번 더 확인하는 절차를 둘 수 있습니다. 가령, Main Window의 Caption을 구할 수 있는 단계까지 대기하도록 만드는 겁니다.

t.Tick += (s, ev) =>
{
    t.Stop();
                
    Process p = Process.Start("WinFormsApp2.exe");
    p.WaitForInputIdle();

    System.Diagnostics.Trace.WriteLine("Waited");

    StringBuilder sb = new StringBuilder(4096);
    while (true)
    {
        IntPtr ptr = p.MainWindowHandle;
        GetWindowText(ptr, sb, sb.Capacity);
        if (sb.Length != 0)
        {
            break;
        }

        Thread.Sleep(16);
    }

    Thread.Sleep(100);
    SetForegroundWindow(this.Handle); 
};

점점 더 복잡해지죠? ^^ 어쩔 수 없습니다, 남이 만든 프로그램과 함께 연동한다는 것은 언제나 이렇게 확률을 높이는 방법을 점점 더 추가하는 식으로 구현하게 됩니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/29/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12886정성태12/20/202114690스크립트: 37. 파이썬 - uwsgi의 --enable-threads 옵션 [2]
12885정성태12/20/202115713오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/202114636개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/202115072오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/202114564개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
12881정성태12/17/202114172개발 환경 구성: 618. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법 (2)
12880정성태12/16/202115162VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
12879정성태12/16/202121705오류 유형: 774. Windows Server 2022 + docker desktop 설치 시 WSL 2로 선택한 경우 "Failed to deploy distro docker-desktop to ..." 오류 발생
12878정성태12/15/202115965개발 환경 구성: 617. 윈도우 WSL 환경에서 같은 종류의 리눅스를 다중으로 설치하는 방법
12877정성태12/15/202115277스크립트: 36. 파이썬 - pymysql 기본 예제 코드
12876정성태12/14/202115141개발 환경 구성: 616. Custom Sources를 이용한 Azure Monitor Metric 만들기
12875정성태12/13/202114012스크립트: 35. python - time.sleep(...) 호출 시 hang이 걸리는 듯한 문제
12874정성태12/13/202113852오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류
12873정성태12/12/202115239오류 유형: 772. 리눅스 - PATH에 등록했는데도 "command not found"가 나온다면?
12872정성태12/12/202115624개발 환경 구성: 615. GoLang과 Python 빌드가 모두 가능한 docker 이미지 만들기
12871정성태12/12/202114683오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/202113753개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/202116456개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/202114827오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
12867정성태12/7/202114596개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
12866정성태12/7/202121493오류 유형: 769. "docker build ..." 시 "failed to solve with frontend dockerfile.v0: failed to read dockerfile ..." 오류
12865정성태12/6/202114839개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
12864정성태12/6/202112512Linux: 46. WSL 환경에서 find 명령을 사용해 파일을 찾는 방법
12863정성태12/4/202114697개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
12862정성태12/3/202112649오류 유형: 768. Golang - 빌드 시 "cmd/go: unsupported GOOS/GOARCH pair linux /amd64" 오류
12861정성태12/3/202116480개발 환경 구성: 609. 파이썬 - "Windows embeddable package"로 개발 환경 구성하는 방법 [1]
... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...