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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...
NoWriterDateCnt.TitleFile(s)
12885정성태12/20/20217826오류 유형: 776. uwsgi-plugin-python3 환경에서 MySQLdb 사용 환경
12884정성태12/20/20216871개발 환경 구성: 620. Windows 10+에서 WMI root/Microsoft/Windows/WindowsUpdate 네임스페이스 제거
12883정성태12/19/20217736오류 유형: 775. uwsgi-plugin-python3 환경에서 "ModuleNotFoundError: No module named 'django'" 오류 발생
12882정성태12/18/20216842개발 환경 구성: 619. Windows Server에서 WSL을 위한 리눅스 배포본을 설치하는 방법
12881정성태12/17/20217338개발 환경 구성: 618. WSL Ubuntu 20.04에서 파이썬을 위한 uwsgi 설치 방법 (2)
12880정성태12/16/20217154VS.NET IDE: 170. Visual Studio에서 .NET Core/5+ 역어셈블 소스코드 확인하는 방법
12879정성태12/16/202113403오류 유형: 774. Windows Server 2022 + docker desktop 설치 시 WSL 2로 선택한 경우 "Failed to deploy distro docker-desktop to ..." 오류 발생
12878정성태12/15/20218477개발 환경 구성: 617. 윈도우 WSL 환경에서 같은 종류의 리눅스를 다중으로 설치하는 방법
12877정성태12/15/20217116스크립트: 36. 파이썬 - pymysql 기본 예제 코드
12876정성태12/14/20216964개발 환경 구성: 616. Custom Sources를 이용한 Azure Monitor Metric 만들기
12875정성태12/13/20216628스크립트: 35. python - time.sleep(...) 호출 시 hang이 걸리는 듯한 문제
12874정성태12/13/20216618오류 유형: 773. shell script 실행 시 "$'\r': command not found" 오류
12873정성태12/12/20217773오류 유형: 772. 리눅스 - PATH에 등록했는데도 "command not found"가 나온다면?
12872정성태12/12/20217592개발 환경 구성: 615. GoLang과 Python 빌드가 모두 가능한 docker 이미지 만들기
12871정성태12/12/20217665오류 유형: 771. docker: Error response from daemon: OCI runtime create failed
12870정성태12/9/20216224개발 환경 구성: 614. 파이썬 - PyPI 패키지 만들기 (4) package_data 옵션
12869정성태12/8/20218517개발 환경 구성: 613. git clone 실행 시 fingerprint 묻는 단계를 생략하는 방법
12868정성태12/7/20217091오류 유형: 770. twine 업로드 시 "HTTPError: 400 Bad Request ..." 오류 [1]
12867정성태12/7/20216759개발 환경 구성: 612. 파이썬 - PyPI 패키지 만들기 (3) entry_points 옵션
12866정성태12/7/202114146오류 유형: 769. "docker build ..." 시 "failed to solve with frontend dockerfile.v0: failed to read dockerfile ..." 오류
12865정성태12/6/20216857개발 환경 구성: 611. 파이썬 - PyPI 패키지 만들기 (2) long_description, cmdclass 옵션
12864정성태12/6/20215303Linux: 46. WSL 환경에서 find 명령을 사용해 파일을 찾는 방법
12863정성태12/4/20217228개발 환경 구성: 610. 파이썬 - PyPI 패키지 만들기
12862정성태12/3/20215975오류 유형: 768. Golang - 빌드 시 "cmd/go: unsupported GOOS/GOARCH pair linux /amd64" 오류
12861정성태12/3/20218160개발 환경 구성: 609. 파이썬 - "Windows embeddable package"로 개발 환경 구성하는 방법
12860정성태12/1/20216278오류 유형: 767. SQL Server - 127.0.0.1로 접속하는 경우 "Access is denied"가 발생한다면?
... 16  17  18  19  20  21  22  23  24  25  26  27  28  29  [30]  ...