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

비밀번호

댓글 작성자
 




1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13868정성태1/17/20253112Windows: 277. Hyper-V - Windows 11 VM의 Enhanced Session 모드로 로그인을 할 수 없는 문제
13867정성태1/17/20254063오류 유형: 943. Hyper-V에 Windows 11 설치 시 "This PC doesn't currently meet Windows 11 system requirements" 오류
13866정성태1/16/20254265개발 환경 구성: 739. Windows 10부터 바뀐 device driver 서명 방법
13865정성태1/15/20253944오류 유형: 942. C# - .NET Framework 4.5.2 이하의 버전에서 HttpWebRequest로 https 호출 시 "System.Net.WebException" 예외 발생
13864정성태1/15/20253908Linux: 114. eBPF를 위해 필요한 SELinux 보안 정책
13863정성태1/14/20253356Linux: 113. Linux - 프로세스를 위한 전용 SELinux 보안 문맥 지정
13862정성태1/13/20253628Linux: 112. Linux - 데몬을 위한 SELinux 보안 정책 설정
13861정성태1/11/20253907Windows: 276. 명령행에서 원격 서비스를 동기/비동기로 시작/중지
13860정성태1/10/20253614디버깅 기술: 216. WinDbg - 2가지 유형의 식 평가 방법(MASM, C++)
13859정성태1/9/20253971디버깅 기술: 215. Windbg - syscall 이후 실행되는 KiSystemCall64 함수 및 SSDT 디버깅
13858정성태1/8/20254100개발 환경 구성: 738. PowerShell - 원격 호출 시 "powershell.exe"가 아닌 "pwsh.exe" 환경으로 명령어를 실행하는 방법
13857정성태1/7/20254148C/C++: 187. Golang - 콘솔 응용 프로그램을 Linux 데몬 서비스를 지원하도록 변경파일 다운로드1
13856정성태1/6/20253727디버깅 기술: 214. Windbg - syscall 단계까지의 Win32 API 호출 (예: Sleep)
13855정성태12/28/20244459오류 유형: 941. Golang - os.StartProcess() 사용 시 오류 정리
13854정성태12/27/20244558C/C++: 186. Golang - 콘솔 응용 프로그램을 NT 서비스를 지원하도록 변경파일 다운로드1
13853정성태12/26/20244023디버깅 기술: 213. Windbg - swapgs 명령어와 (Ring 0 커널 모드의) FS, GS Segment 레지스터
13852정성태12/25/20244486디버깅 기술: 212. Windbg - (Ring 3 사용자 모드의) FS, GS Segment 레지스터파일 다운로드1
13851정성태12/23/20244238디버깅 기술: 211. Windbg - 커널 모드 디버깅 상태에서 사용자 프로그램을 디버깅하는 방법
13850정성태12/23/20244741오류 유형: 940. "Application Information" 서비스를 중지한 경우, "This file does not have an app associated with it for performing this action."
13849정성태12/20/20244883디버깅 기술: 210. Windbg - 논리(가상) 주소를 Segmentation을 거쳐 선형 주소로 변경
13848정성태12/18/20244820디버깅 기술: 209. Windbg로 알아보는 Prototype PTE파일 다운로드2
13847정성태12/18/20244855오류 유형: 939. golang - 빌드 시 "unknown directive: toolchain" 오류 빌드 시 이런 오류가 발생한다면?
13846정성태12/17/20245057디버깅 기술: 208. Windbg로 알아보는 Trans/Soft PTE와 2가지 Page Fault 유형파일 다운로드1
13845정성태12/16/20244526디버깅 기술: 207. Windbg로 알아보는 PTE (_MMPTE)
13844정성태12/14/20245212디버깅 기술: 206. Windbg로 알아보는 PFN (_MMPFN)파일 다운로드1
13843정성태12/13/20244391오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
1  2  [3]  4  5  6  7  8  9  10  11  12  13  14  15  ...