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

비밀번호

댓글 작성자
 




... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...
NoWriterDateCnt.TitleFile(s)
12410정성태11/12/202017582디버깅 기술: 174. windbg - System.TypeLoadException 예외 분석 사례
12409정성태11/12/202019423.NET Framework: 968. C# 9.0의 Function pointer를 이용한 함수 주소 구하는 방법파일 다운로드1
12408정성태11/9/202034670도서: 시작하세요! C# 9.0 프로그래밍 [8]
12407정성태11/9/202019764.NET Framework: 967. "clr!JIT_DbgIsJustMyCode" 호출이 뭘까요?
12406정성태11/8/202020754.NET Framework: 966. C# 9.0 - (15) 최상위 문(Top-level statements) [5]파일 다운로드1
12405정성태11/8/202018618.NET Framework: 965. C# 9.0 - (14) 부분 메서드에 대한 새로운 기능(New features for partial methods)파일 다운로드1
12404정성태11/7/202019239.NET Framework: 964. C# 9.0 - (13) 모듈 이니셜라이저(Module initializers)파일 다운로드1
12403정성태11/7/202018147.NET Framework: 963. C# 9.0 - (12) foreach 루프에 대한 GetEnumerator 확장 메서드 지원(Extension GetEnumerator)파일 다운로드1
12402정성태11/7/202019636.NET Framework: 962. C# 9.0 - (11) 공변 반환 형식(Covariant return types) [1]파일 다운로드1
12401정성태11/5/202018905VS.NET IDE: 153. 닷넷 응용 프로그램에서의 "My Code" 범위와 "Enable Just My Code"의 역할 [1]
12400정성태11/5/202015135오류 유형: 679. Visual Studio - "Source Not Found" 창에 "Decompile source code" 링크가 없는 경우
12399정성태11/5/202018655.NET Framework: 961. C# 9.0 - (10) 대상으로 형식화된 조건식(Target-typed conditional expressions)파일 다운로드1
12398정성태11/4/202018166오류 유형: 678. Windows Server 2008 R2 환경에서 Powershell을 psexec로 원격 실행할 때 hang이 발생하는 문제
12397정성태11/4/202018187.NET Framework: 960. C# - 조건 연산자(?:)를 사용하는 경우 달라지는 메서드 선택 사례파일 다운로드1
12396정성태11/3/202015207VS.NET IDE: 152. Visual Studio - "Tools" / "External Tools..."에 등록된 외부 명령어에 대한 단축키 설정 방법
12395정성태11/3/202017981오류 유형: 677. SSMS로 DB 접근 시 The server principal "..." is not able to access the database "..." under the current security context.
12394정성태11/3/202015612오류 유형: 676. cacls - The Recycle Bin on ... is corrupted. Do you want to empty the Recycle Bin for this drive?
12393정성태11/3/202015281오류 유형: 675. Visual Studio - 닷넷 응용 프로그램 디버깅 시 Disassembly 창에서 BP 설정할 때 "Error while processing breakpoint." 오류
12392정성태11/2/202019825.NET Framework: 959. C# 9.0 - (9) 레코드(Records) [4]파일 다운로드1
12390정성태11/1/202019477디버깅 기술: 173. windbg - System.Configuration.ConfigurationErrorsException 예외 분석 방법
12389정성태11/1/202018617.NET Framework: 958. C# 9.0 - (8) 정적 익명 함수 (static anonymous functions)파일 다운로드1
12388정성태10/29/202017674오류 유형: 674. 어느 순간부터 닷넷 응용 프로그램 실행 시 System.Configuration.ConfigurationErrorsException 예외가 발생한다면?
12387정성태10/28/202018461.NET Framework: 957. C# - static 필드의 정보가 GC Heap에 저장될까요? [3]파일 다운로드1
12386정성태10/28/202019200Linux: 34. 사용자 정보를 함께 출력하는 리눅스의 ps 명령어 사용 방법
12385정성태10/28/202016544오류 유형: 673. openssl - req: No value provided for Subject Attribute CN, skipped
12384정성태10/27/202018870오류 유형: 672. AllowPartiallyTrustedCallers 특성이 적용된 어셈블리의 struct 멤버 메서드를 재정의하면 System.Security.VerificationException 예외 발생
... [61]  62  63  64  65  66  67  68  69  70  71  72  73  74  75  ...