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

C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법

Windows에서 기본 제공하는 "Find", "Find and Replace" 대화창이 있는데요,

Find and Replace Dialog Boxes
; https://learn.microsoft.com/en-us/windows/win32/dlgbox/find-and-replace-dialog-boxes

find_dlg_1.png

이걸 혹시 C#에서도 사용할 수 있을까요? 일단 ^^ C/C++로의 대략적인 사용법은 다음의 글에서 설명하고 있으니,

Modality, part 1: UI-modality vs code-modality
; https://devblogs.microsoft.com/oldnewthing/20050218-00/?p=36413

적절하게 PInvoke를 활용하면 당연히 C#에서도 호출할 수 있습니다. 실제로 한번 만들어 볼까요? ^^




간단하게 C# Windows Forms 프로젝트를 생성한 다음, 가장 먼저 할 일은 "Find" 대화창에서 "Find Next" 버튼이 눌린 것에 대한 알림을 받기 위한 메시지를 등록해야 합니다.

public class FindTextDialog
{
    const string FINDMSGSTRINGW = "commdlg_FindReplace"; // commdlg.h
    const string FINDMSGSTRING = FINDMSGSTRINGW; // commdlg.h

    uint _msg_FindString = 0;

    [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern uint RegisterWindowMessage(string lpString);

    public unsafe FindTextDialog(IntPtr owner)
    {
        _msg_FindString = RegisterWindowMessage(FINDMSGSTRING);
    }
}

이어서 FINDREPLACEW 구조체를 초기화해 Find 대화창을 띄우는 코드를 작성합니다.

public class FindTextDialog : IDisposable
{
    //...[생략]...

    [DllImport("Comdlg32.dll", SetLastError = true, CharSet = CharSet.Auto)]
    static extern IntPtr FindText(ref FINDREPLACEW unnamedParam1);

    FINDREPLACEW _findItem = new FINDREPLACEW();

    IntPtr _pFindWhatBuffer = IntPtr.Zero;
    IntPtr _hwndParent = IntPtr.Zero;

    public unsafe FindTextDialog(IntPtr owner)
    {
        _hwndParent = owner;

        _pFindWhatBuffer = new IntPtr(Marshal.AllocHGlobal(80));
        Unsafe.InitBlockUnaligned((byte*)_pFindWhatBuffer.ToPointer(), 0, 80);

        _findItem.lStructSize = (uint)Marshal.SizeOf(_findItem);
        _findItem.hwndOwner = _hwndParent;
        _findItem.hInstance = Marshal.GetHINSTANCE(typeof(FindTextDialog).Module);
        _findItem.lpstrFindWhat = _pFindWhatBuffer;
        _findItem.wFindWhatLen = 80;

        //...[생략]...
    }

    public void CreateDialog()
    {
        if (_hWnd != IntPtr.Zero)
        {
            return;
        }
        
        if (_msg_FindString != 0)
        {
            _hWnd = FindText(ref _findItem); // Find 대화창 생성 (modeless 방식)
        }
    }

    public void Dispose()
    {
        if (_pFindWhatBuffer != IntPtr.Zero)
        {
            Marshal.FreeHGlobal(_pFindWhatBuffer);
            _pFindWhatBuffer = IntPtr.Zero;
        }
    }
}

[StructLayout(LayoutKind.Sequential)]
unsafe struct FINDREPLACEW
{
    public uint lStructSize;        // size of this struct 0x20
    public IntPtr hwndOwner;          // handle to owner's window
    public IntPtr hInstance;          // instance handle of.EXE that
                                      //   contains cust. dlg. template
    public uint Flags;              // one or more of the FR_??
    public IntPtr lpstrFindWhat;      // ptr. to search string
    public char* lpstrReplaceWith;   // ptr. to replace string
    public ushort wFindWhatLen;       // size of find buffer
    public ushort wReplaceWithLen;    // size of replace buffer

    public IntPtr lCustData;          // data passed to hook fn.
    public delegate*<IntPtr, uint, uint, IntPtr, IntPtr> lpfnHook;           // ptr. to hook fn. or NULL
    public char* lpTemplateName;     // custom template name
}

위와 같이 만들었으면 이제 다음과 같은 코드로 FindTextDialog를 사용할 수 있습니다.

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

namespace WinFormsApp1
{
    public unsafe partial class Form1 : Form
    {
        [AllowNull]
        FindTextDialog _dlg;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            _dlg = new FindTextDialog(this.Handle);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            _dlg.CreateDialog();
        }

        protected override void OnFormClosed(FormClosedEventArgs e)
        {
            _dlg.Dispose();
            _dlg = null;

            base.OnFormClosed(e);
        }
    }
}

일단, 대화창은 띄웠지만 이게 끝이 아니죠? ^^ 당연히 Find 대화창에서 "Find Next" 버튼을 눌렀을 때 (이전에 RegisterWindowMessage로 등록했던) 메시지를 받아서 처리를 해야 합니다.

이 과정은 WndProc에 다음과 같이 처리할 수 있습니다.

namespace WinFormsApp1
{
    public unsafe partial class Form1 : Form
    {
        // ...[생략]...

        protected override void WndProc(ref Message m)
        {
            if (_dlg != null && _dlg.IsFindMessage(m.Msg) == true)
            {
                OnFindReplace(m.HWnd, (FINDREPLACEW*)m.LParam.ToPointer());
                return;
            }
            
            base.WndProc(ref m);
       }

        unsafe void OnFindReplace(IntPtr hwnd, FINDREPLACEW* pfr)
        {
            if (_dlg.HasCloseFlag())
            {
                _dlg.Close();
                return;
            }

            if (_dlg.HasFindNextFlag())
            {
                MessageBox.Show(_dlg.Text); // Find 대화창에서 사용자가 입력한 문자열
            }
        }
    }
}

public class FindTextDialog : IDisposable
{
    // ...[생략]...

    uint _msg_FindString = 0;
    public bool IsFindMessage(int msg) => msg == (int)_msg_FindString;
    FINDREPLACEW _findItem = new FINDREPLACEW();

    public bool HasFindNextFlag()
    {
        return (_findItem.Flags & FR_FINDNEXT) == FR_FINDNEXT;
    }

    public bool HasCloseFlag()
    {
        if (HasFindNextFlag())
        {
            return false;
        }
        
        return (_findItem.Flags & FR_DIALOGTERM) == FR_DIALOGTERM;
    }

    // ...[생략]...
}

간단하죠? 만약 동일한 기능의 대화창이 필요하다면 굳이 Form 하나를 만들 필요 없이 저 Win32 대화창을 사용하는 것도 그리 나쁘진 않은 선택일 것입니다. ^^

^^ 여기서 한 가지 재미있는 점은, oldnewthing의 원래 코드는 OnFindReplace 함수가 다음과 같이 정의돼 있다는 점입니다.

void OnFindReplace(HWND hwnd, FINDREPLACE *pfr)
{
  if (pfr->Flags & FR_DIALOGTERM) {
      DestroyWindow(g_hwndFR);
      g_hwndFR = NULL;
  }
}

Find 대화창을 닫기 했을 때, 즉 "Cancel" 버튼이나 윈도우 우측 상단의 Close 버튼을 눌렀을 때 FR_DIALOGTERM 플래그가 설정되는데요, 위의 코드는 그것을 감지해 Find 대화창을 종료하고 있습니다.

그런데, 위의 코드를 테스트하다 보면 문제를 하나 발견하게 됩니다. 처음 FindText 대화창을 띄울 때는 상관없지만, 재차 FindText API를 호출해 대화창을 띄우게 되면 "Find Next" 버튼을 누르는 경우까지도 FR_DIALOGTERM 플래그가 함께 설정된다는 점입니다. 따라서 코드를 다음과 같이 변경해야 합니다. (위의 C# 코드는 아래의 변경이 반영된 것입니다.)

void OnFindReplace(HWND hwnd, FINDREPLACE* pfr)
{
    if (pfr->Flags & FR_FINDNEXT) {
        // ... 처리 ...
    }
    else if (pfr->Flags & FR_DIALOGTERM) {
        // DestroyWindow(g_hwndFR); // 게다가 DestroyWindow 호출도 필요 없음!
        g_hwndFR = NULL;
    }
}

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




마지막으로 "Modality, part 1: UI-modality vs code-modality" 글에서는 message loop 내에 IsDialogMessage 함수를 호출하고 있습니다.

사실, C# Windows Forms 응용 프로그램은 IsDialogMessage Win32 API를 사용하지 않고 그에 상응하는 기능들이 C# 코드로 녹아들어 있습니다. 그렇기 때문에 이걸 구현하지 않아도 Find 대화창에서의 특수 키 입력이 모두 동작합니다. (예를 들어 Tab 키를 눌러 입력 포커스 이동)




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

[연관 글]






[최초 등록일: ]
[최종 수정일: 3/20/2023]

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)
13697정성태7/26/2024386닷넷: 2283. C# - async 메서드에서의 lock/Monitor.Enter/Exit 잠금 처리파일 다운로드1
13696정성태7/26/2024297오류 유형: 920. dotnet publish - error NETSDK1047: Assets file '...\obj\project.assets.json' doesn't have a target for '...'
13695정성태7/25/2024330닷넷: 2282. C# - Lock / Wait 상태에서도 STA COM 메서드 호출 처리파일 다운로드1
13694정성태7/25/2024306닷넷: 2281. C# - ASP.NET Core Web App의 Request 용량 상한값 (Kestrel, IIS)
13693정성태7/24/2024463개발 환경 구성: 717. Visual Studio - C# 프로젝트에서 레지스트리에 등록하지 않은 COM 개체 참조 및 사용 방법파일 다운로드1
13692정성태7/24/2024479디버깅 기술: 199. Windbg - 리눅스에서 뜬 닷넷 응용 프로그램 덤프 파일에 포함된 DLL의 Export Directory 탐색
13691정성태7/23/2024529디버깅 기술: 198. Windbg - 스레드의 Win32 Message Queue 정보 조회
13690정성태7/23/2024536오류 유형: 919. Visual C++ 리눅스 프로젝트 - error : ‘u8’ was not declared in this scope
13689정성태7/22/2024530디버깅 기술: 197. Windbg - PE 포맷의 Export Directory 탐색
13688정성태7/21/2024664닷넷: 2280. C# - Lock / Wait 상태에서도 일부 Win32 메시지 처리파일 다운로드1
13687정성태7/19/2024675닷넷: 2279. C# - PostThreadMessage로 보낸 메시지를 Windows Forms에서 수신하는 방법파일 다운로드1
13686정성태7/19/2024630오류 유형: 918. Visual Studio - ATL Simple Object 추가 시 error C2065: 'IDR_...': undeclared identifier
13685정성태7/19/2024701스크립트: 66. Windows 디렉터리 경로를 WSL의 /mnt 포맷으로 구하는 방법 - 두 번째 이야기
13684정성태7/19/2024877닷넷: 2278. C# - 문자열 보간식 사례
13683정성태7/18/2024901오류 유형: 917. ClrMD - Linux 환경의 .NET 5 덤프 분석 시 hang 현상
13682정성태7/18/2024955닷넷: 2277. WPF - 스레드에 종속되는 DependencyObject파일 다운로드1
13681정성태7/17/20241018닷넷: 2276. C# 13 - (2) 메서드 그룹의 자연 타입 개선 (메서드 추론 개선)파일 다운로드1
13680정성태7/16/20241031닷넷: 2275. C# - Method Group, Natural Type, function_type파일 다운로드1
13679정성태7/16/20241043Linux: 75. Linux - C++ (getaddrinfo 등을 담고 있는) libnss 정적 링크
13678정성태7/15/2024898VS.NET IDE: 191. Visual Studio 2022 - .NET 5 프로젝트를 Docker Support로 실행했을 때 오류
13677정성태7/15/20241032오류 유형: 916. MSBuild - CheckEolTargetFramework (warning NETSDK1138)
13676정성태7/14/2024996Linux: 75. gdb에서 glibc의 함수에 Breakpoint 걸기
13675정성태7/13/2024990C/C++: 166. C/C++ - DLL에서 template 함수를 export하는 방법파일 다운로드1
13674정성태7/13/20241044오류 유형: 915. Unhandled Exception: Microsoft.Diagnostics.NETCore.Client.ServerNotAvailableException: Unable to connect to Process
13673정성태7/11/20241066닷넷: 2274. C# 13 - (1) 신규 이스케이프 시퀀스 '\e'파일 다운로드1
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...