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

비밀번호

댓글 작성자
 




... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...
NoWriterDateCnt.TitleFile(s)
12487정성태1/13/202116518.NET Framework: 1004. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법파일 다운로드1
12486정성태1/12/202118254.NET Framework: 1003. x64 환경에서 참조형의 기본 메모리 소비는 얼마나 될까요? [1]
12485정성태1/11/202118447Graphics: 38. C# - OpenCvSharp.VideoWriter에 BMP 파일을 1초씩 출력하는 예제 [2]파일 다운로드1
12484정성태1/9/202120017.NET Framework: 1002. C# - ReadOnlySequence<T> 소개파일 다운로드1
12483정성태1/8/202116238개발 환경 구성: 521. dotPeek - 훌륭한 역어셈블 소스 코드 생성 도구
12482정성태1/8/202117988.NET Framework: 1001. C# - 제네릭 타입/메서드에서 사용 시 경우에 따라 CS8377 컴파일 에러
12481정성태1/7/202118056.NET Framework: 1000. C# - CS8344 컴파일 에러: ref struct 타입의 사용 제한 메서드파일 다운로드1
12480정성태1/6/202120823.NET Framework: 999. C# - ArrayPool<T>와 MemoryPool<T> 소개파일 다운로드1
12479정성태1/6/202118009.NET Framework: 998. C# - OWIN 예제 프로젝트 만들기
12478정성태1/5/202120692.NET Framework: 997. C# - ArrayPool<T> 소개파일 다운로드1
12477정성태1/5/202121790기타: 79. github 코드 검색 방법 [1]
12476정성태1/5/202118164.NET Framework: 996. C# - 닷넷 코어에서 다른 스레드의 callstack을 구하는 방법파일 다운로드1
12475정성태1/5/202121900.NET Framework: 995. C# - Span<T>와 Memory<T> [1]파일 다운로드1
12474정성태1/4/202118662.NET Framework: 994. C# - (.NET Core 2.2부터 가능한) 프로세스 내부에서 CLR ETW 이벤트 수신 [1]파일 다운로드1
12473정성태1/4/202117235.NET Framework: 993. .NET 런타임에 따라 달라지는 정적 필드의 초기화 유무 [1]파일 다운로드1
12472정성태1/3/202117249디버깅 기술: 178. windbg - 디버그 시작 시 스크립트 실행
12471정성태1/1/202118046.NET Framework: 992. C# - .NET Core 3.0 이상부터 제공하는 runtimeOptions의 rollForward 옵션 [1]
12470정성태12/30/202018158.NET Framework: 991. .NET 5 응용 프로그램에서 WinRT API 호출 [1]파일 다운로드1
12469정성태12/30/202022619.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스 [1]파일 다운로드1
12468정성태12/30/202019024Windows: 186. CMD Shell의 "Defaults"와 "Properties"에서 폰트 정보가 다른 문제 [1]
12467정성태12/29/202019020.NET Framework: 989. HttpContextAccessor를 통해 이해하는 AsyncLocal<T> [1]파일 다운로드1
12466정성태12/29/202016550.NET Framework: 988. C# - 지연 실행이 꼭 필요한 상황이 아니라면 singleton 패턴에서 DCLP보다는 static 초기화를 권장 [1]파일 다운로드1
12465정성태12/29/202020240.NET Framework: 987. .NET Profiler - FunctionID와 연관된 ClassID를 구할 수 없는 문제
12464정성태12/29/202018547.NET Framework: 986. pptfont.exe - PPT 파일에 숨겨진 폰트 설정을 일괄 삭제
12463정성태12/29/202017466개발 환경 구성: 520. RDP(mstsc.exe)의 다중 모니터 옵션 /multimon, /span
12462정성태12/27/202019449디버깅 기술: 177. windbg - (ASP.NET 환경에서 유용한) netext 확장
... 46  47  48  49  50  51  52  53  54  55  56  57  [58]  59  60  ...