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)
13843정성태12/13/20244381오류 유형: 938. Docker container 내에서 빌드 시 error MSB3021: Unable to copy file "..." to "...". Access to the path '...' is denied.
13842정성태12/12/20244534디버깅 기술: 205. Windbg - KPCR, KPRCB
13841정성태12/11/20244866오류 유형: 937. error MSB4044: The "ValidateValidArchitecture" task was not given a value for the required parameter "RemoteTarget"
13840정성태12/11/20244437오류 유형: 936. msbuild - Your project file doesn't list 'win' as a "RuntimeIdentifier"
13839정성태12/11/20244859오류 유형: 936. msbuild - error CS1617: Invalid option '12.0' for /langversion. Use '/langversion:?' to list supported values.
13838정성태12/4/20244595오류 유형: 935. Windbg - Breakpoint 0's offset expression evaluation failed.
13837정성태12/3/20245058디버깅 기술: 204. Windbg - 윈도우 핸들 테이블 (3) - Windows 10 이상인 경우
13836정성태12/3/20244624디버깅 기술: 203. Windbg - x64 가상 주소를 물리 주소로 변환 (페이지 크기가 2MB인 경우)
13835정성태12/2/20245071오류 유형: 934. Azure - rm: cannot remove '...': Directory not empty
13834정성태11/29/20245287Windows: 275. C# - CUI 애플리케이션과 Console 윈도우 (Windows 10 미만의 Classic Console 모드인 경우) [1]파일 다운로드1
13833정성태11/29/20244979개발 환경 구성: 737. Azure Web App에서 Scale-out으로 늘어난 리눅스 인스턴스에 SSH 접속하는 방법
13832정성태11/27/20244909Windows: 274. Windows 7부터 도입한 conhost.exe
13831정성태11/27/20244382Linux: 111. eBPF - BPF_MAP_TYPE_PERF_EVENT_ARRAY, BPF_MAP_TYPE_RINGBUF에 대한 다양한 용어들
13830정성태11/25/20245185개발 환경 구성: 736. 파이썬 웹 앱을 Azure App Service에 배포하기
13829정성태11/25/20245162스크립트: 67. 파이썬 - Windows 버전에서 함께 설치되는 py.exe
13828정성태11/25/20244440개발 환경 구성: 735. Azure - 압축 파일을 이용한 web app 배포 시 디렉터리 구분이 안 되는 문제파일 다운로드1
13827정성태11/25/20245091Windows: 273. Windows 환경의 파일 압축 방법 (tar, Compress-Archive)
13826정성태11/21/20245320닷넷: 2313. C# - (비밀번호 등의) Console로부터 입력받을 때 문자열 출력 숨기기(echo 끄기)파일 다운로드1
13825정성태11/21/20245667Linux: 110. eBPF / bpf2go - BPF_RINGBUF_OUTPUT / BPF_MAP_TYPE_RINGBUF 사용법
13824정성태11/20/20244750Linux: 109. eBPF / bpf2go - BPF_PERF_OUTPUT / BPF_MAP_TYPE_PERF_EVENT_ARRAY 사용법
13823정성태11/20/20245289개발 환경 구성: 734. Ubuntu에 docker, kubernetes (k3s) 설치
13822정성태11/20/20245155개발 환경 구성: 733. Windbg - VirtualBox VM의 커널 디버거 연결 시 COM 포트가 없는 경우
13821정성태11/18/20245079Linux: 108. Linux와 Windows의 프로세스/스레드 ID 관리 방식
13820정성태11/18/20245249VS.NET IDE: 195. Visual C++ - C# 프로젝트처럼 CopyToOutputDirectory 항목을 추가하는 방법
13819정성태11/15/20244490Linux: 107. eBPF - libbpf CO-RE의 CONFIG_DEBUG_INFO_BTF 빌드 여부에 대한 의존성
13818정성태11/15/20245287Windows: 272. Windows 11 24H2 - sudo 추가
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...