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)
13305정성태4/1/20234038Windows: 242. Win32 - 시간 만료를 갖는 MessageBox 대화창 구현 (쉬운 버전)파일 다운로드1
13304정성태3/31/20234390VS.NET IDE: 181. Visual Studio - C/C++ 프로젝트에 application manifest 적용하는 방법
13303정성태3/30/20233735Windows: 241. 환경 변수 %PATH%에 DLL을 찾는 규칙
13302정성태3/30/20234363Windows: 240. RDP 환경에서 바뀌는 %TEMP% 디렉터리 경로
13301정성태3/29/20234457Windows: 239. C/C++ - Windows 10 Version 1607부터 지원하는 /DEPENDENTLOADFLAG 옵션파일 다운로드1
13300정성태3/28/20234100Windows: 238. Win32 - Modal UI 창에 올바른 Owner(HWND)를 설정해야 하는 이유
13299정성태3/27/20233871Windows: 237. Win32 - 모든 메시지 루프를 탈출하는 WM_QUIT 메시지
13298정성태3/27/20233829Windows: 236. Win32 - MessageBeep 소리가 안 들린다면?
13297정성태3/26/20234491Windows: 235. Win32 - Code Modal과 UI Modal
13296정성태3/25/20233836Windows: 234. IsDialogMessage와 협업하는 WM_GETDLGCODE Win32 메시지 [1]파일 다운로드1
13295정성태3/24/20234118Windows: 233. Win32 - modeless 대화창을 modal처럼 동작하게 만드는 방법파일 다운로드1
13294정성태3/22/20234289.NET Framework: 2105. LargeAddressAware 옵션이 적용된 닷넷 32비트 프로세스의 가용 메모리 - 두 번째
13293정성태3/22/20234347오류 유형: 853. dumpbin - warning LNK4048: Invalid format file; ignored
13292정성태3/21/20234466Windows: 232. C/C++ - 일반 창에도 사용 가능한 IsDialogMessage파일 다운로드1
13291정성태3/20/20234838.NET Framework: 2104. C# Windows Forms - WndProc 재정의와 IMessageFilter 사용 시의 차이점
13290정성태3/19/20234332.NET Framework: 2103. C# - 윈도우에서 기본 제공하는 FindText 대화창 사용법파일 다운로드1
13289정성태3/18/20233523Windows: 231. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 자식 윈도우를 생성하는 방법파일 다운로드1
13288정성태3/17/20233636Windows: 230. Win32 - 대화창의 DLU 단위를 pixel로 변경하는 방법파일 다운로드1
13287정성태3/16/20233803Windows: 229. Win32 - 대화창 템플릿의 2진 리소스를 읽어들여 윈도우를 직접 띄우는 방법파일 다운로드1
13286정성태3/15/20234243Windows: 228. Win32 - 리소스에 포함된 대화창 Template의 2진 코드 해석 방법
13285정성태3/14/20233831Windows: 227. Win32 C/C++ - Dialog Procedure를 재정의하는 방법파일 다운로드1
13284정성태3/13/20234055Windows: 226. Win32 C/C++ - Dialog에서 값을 반환하는 방법파일 다운로드1
13283정성태3/12/20233592오류 유형: 852. 파이썬 - TypeError: coercing to Unicode: need string or buffer, NoneType found
13282정성태3/12/20233921Linux: 58. WSL - nohup 옵션이 필요한 경우
13281정성태3/12/20233850Windows: 225. 윈도우 바탕화면의 아이콘들이 넓게 퍼지는 경우 [2]
13280정성태3/9/20234603개발 환경 구성: 670. WSL 2에서 호스팅 중인 TCP 서버를 외부에서 접근하는 방법
1  2  3  4  5  6  7  8  9  10  11  12  [13]  14  15  ...