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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...
NoWriterDateCnt.TitleFile(s)
12437정성태12/1/202017961VS.NET IDE: 155. pfx의 암호 키 파일을 Visual Studio 없이 등록하는 방법
12436정성태12/1/202018117오류 유형: 687. .NET Core 2.2 빌드 - error MSB4018: The "RazorTagHelper" task failed unexpectedly.
12435정성태12/1/202025202Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 [1]파일 다운로드1
12434정성태11/30/202019034Windows: 180. C# - dynamicport 값의 범위를 알아내는 방법
12433정성태11/29/202017771Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY파일 다운로드1
12432정성태11/29/202019268Windows: 178. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR [1]파일 다운로드1
12431정성태11/27/202016108.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/202018516오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/202018602디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/202016740VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/202017608.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/202015998오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/202017638VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/202017949VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202018587.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/202016011.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/202015289.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/202015220오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
12419정성태11/19/202016109VC++: 139. Visual C++ - .NET Core의 nethost.lib와 정적 링크파일 다운로드1
12418정성태11/19/202018356오류 유형: 683. Visual C++ - error LNK2038: mismatch detected for 'RuntimeLibrary': value 'MT_StaticRelease' doesn't match value 'MDd_DynamicDebug'파일 다운로드1
12417정성태11/19/202016069오류 유형: 682. Visual C++ - warning LNK4099: PDB '...pdb' was not found with '...lib(pch.obj)' or at '...pdb'; linking object as if no debug info
12416정성태11/19/202017153오류 유형: 681. Visual C++ - error LNK2001: unresolved external symbol _CrtDbgReport
12415정성태11/18/202017411.NET Framework: 971. UnmanagedCallersOnly 특성과 DNNE 사용파일 다운로드1
12414정성태11/18/202019525VC++: 138. x64 빌드에서 extern "C"가 아닌 경우 ___cdecl name mangling 적용 [4]파일 다운로드1
12413정성태11/17/202018508.NET Framework: 970. .NET 5 / .NET Core - UnmanagedCallersOnly 특성을 사용한 함수 내보내기파일 다운로드1
12412정성태11/16/202020662.NET Framework: 969. .NET Framework 및 .NET 5 - UnmanagedCallersOnly 특성 사용파일 다운로드1
... 46  47  48  49  50  51  52  53  54  55  56  57  58  59  [60]  ...