본문 바로가기
C#

[C#] WebView2 Control 이용 PDF 파일 오픈 후 Key , mouse 입력 인쇄 시도

by Hwoarang757 2022. 5. 26.

[C#] WebView2 Control 이용 PDF 오픈 후 Key , mouse 입력 인쇄 시도 

WebView2 Control을 이용하여 IE Edge 브라우져에서 PDF 파일을 오픈 한 후 

await webView2.CoreWebView2.ExecuteScriptAsync("window.print();"); 를 호출 하여 프린트 다이얼로그를 표시 한 후

해당 프린트 다이얼로그의 Handle을 찾는 것을 시도 후 마우스 왼쪽 버튼을 클릭 한 후 엔터 키를 입력 하게 시도 하였습니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WebView2PrintTest
{
    public partial class FormWebView : Form
    {
        const uint MOUSEMOVE = 0x0001;
        const uint ABSOLUTEMOVE = 0x8000;
        const uint LBUTTONDOWN = 0x0002;
        const uint LBUTTONUP = 0x0004;
        const uint RBUTTONDOWN = 0x0008;
        const uint RBUTTONUP = 0x00010;

        private string _filePath;
        public FormWebView()
        {
            InitializeComponent();
        }

        public FormWebView(string _filePath)
        {
            InitializeComponent();
            this._filePath = _filePath;
        }


        [System.Runtime.InteropServices.DllImport("user32.dll")]
        public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindowEx(IntPtr hWnd1, IntPtr hWnd2, string lpsz1, string lpsz2);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll")]
        public static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern void mouse_event(uint dwFlags, uint dx, uint dy, uint dwData, int dwExtraInfo);

        [DllImport("user32.dll")]
        public static extern bool GetWindowPlacement(IntPtr handle, ref WINDOWPLACEMENT lpwndpl);


        public struct WINDOWPLACEMENT
        {
            public int length;
            public int flags;
            public ShowWindowCommands showCmd;
            public System.Drawing.Point ptMinPosition;
            public System.Drawing.Point ptMaxPosition;
            public System.Drawing.Rectangle rcNormalPosition;
        }

        public enum ShowWindowCommands : int
        {
            Hide = 0,
            Normal = 1,
            Minimized = 2,
            Maximized = 3,
        }


        IntPtr nCurPtr = IntPtr.Zero;

        public bool Ignored { get; set; } = false;

        private void FormWebView_Load(object sender, EventArgs e)
        {

        }

        private async void FormWebView_Shown(object sender, EventArgs e)
        {
            this.TopMost = false;
            this.WindowState = FormWindowState.Maximized;
            webView2.Size = this.Size;
            

            await webView2.EnsureCoreWebView2Async();

            webView2.Source = new Uri(string.Format(@"file:///{0}",_filePath.Replace(@"\" ,"/")) );
            webView2.NavigationCompleted += WebView2_NavigationCompleted;
        }



        private async void WebView2_NavigationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationCompletedEventArgs e)
        {
            await webView2.CoreWebView2.ExecuteScriptAsync("window.print();");
            Delay(2000);
            

            IntPtr printHandle = FindWindowEx(webView2.Handle, IntPtr.Zero, "Intermediate D3D Window", "");
            Debug.WriteLine("webview Handle=" + webView2.Handle.ToString());

            //IntPtr wm1 = FindWindowEx(this.Handle, IntPtr.Zero, "WindowsForms10.Window.8.app.0.141b42a_r8_ad1", "");
            IntPtr wm2 = FindWindowEx(webView2.Handle, IntPtr.Zero, "Chrome_WidgetWin_0", "");
            IntPtr wm3 = FindWindowEx(wm2, IntPtr.Zero, "Chrome_WidgetWin_1", webView2.CoreWebView2.DocumentTitle );
            IntPtr wm4 = FindWindowEx(wm3, IntPtr.Zero, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window");
            IntPtr wm5 = FindWindowEx(wm3, wm4, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window");


            Debug.WriteLine("webView2=" + webView2.Handle);
            Debug.WriteLine("Chrome_WidgetWin_0=" + wm2);
            Debug.WriteLine("Chrome_WidgetWin_1=" + wm3);
            Debug.WriteLine("Chrome_RenderWidgetHostHWND=" + wm4);
            Debug.WriteLine("Chrome_RenderWidgetHostHWND_Second=" + wm5);

            bool compare = false;
            bool bMacroResult = false;
            if (wm5 == IntPtr.Zero)
            {
                wm5 = wm4;
                compare = true;
            }
            else if (wm4.ToInt64() > wm5.ToInt64())
            {
                wm5 = wm4;
                compare = true;
            }
            //return;
            // 창의 위치를 구한다.
            Size size = new Size();
            Point point = new Point();

            GetWindowPos(wm5, ref point, ref size);

            Cursor.Position = new Point(point.X + 150, point.Y + 100);
            mouse_event(LBUTTONDOWN, 0, 0, 0, 0);
            Delay(50);
            mouse_event(LBUTTONUP, 0, 0, 0, 0);
            SetForegroundWindow(wm5);
            Delay(50);
            SendKeys.Send("{ENTER}");

            Delay(500);

            Debug.WriteLine("Handle=" + FindWindowEx(wm3, IntPtr.Zero, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window"));

            IntPtr tmpPtr = IntPtr.Zero;
            if (compare) tmpPtr = FindWindowEx(wm3, IntPtr.Zero, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window");
            else tmpPtr = FindWindowEx(wm3, wm4, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window");

            short sTryCnt = 0;

            if (tmpPtr != wm5) bMacroResult = true;

            // 10번만 재시도 한다. -_-;; , 동일한 핸들이 존재 하는 것을 확인 한다.
            while (tmpPtr == wm5 )
            {
                if (compare) tmpPtr = FindWindowEx(wm3, IntPtr.Zero, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window");
                else tmpPtr = FindWindowEx(wm3, wm4, "Chrome_RenderWidgetHostHWND", "Chrome Legacy Window");

                Debug.WriteLine("Chrome_RenderWidgetHostHWND=" + tmpPtr);

                GetWindowPos(wm5, ref point, ref size);

                Cursor.Position = new Point(point.X + 400, point.Y + 150);
                mouse_event(LBUTTONDOWN, 0, 0, 0, 0);
                Delay(50);
                mouse_event(LBUTTONUP, 0, 0, 0, 0);
                SetForegroundWindow(wm5);
                Delay(50);
                SendKeys.Send("{ENTER}");


                Debug.WriteLine("Retry Print");
                sTryCnt++;

                if (sTryCnt >= 9)
                {
                    bMacroResult = false;
                    break;
                }
                bMacroResult = true;
            }
            Debug.WriteLine("End Print sTryCnt=" + sTryCnt);

            if (bMacroResult) this.Close();

        }

        private void GetWindowPos(IntPtr hwnd, ref Point point, ref Size size)
        {
            WINDOWPLACEMENT placement = new WINDOWPLACEMENT();
            placement.length = Marshal.SizeOf(placement);

            GetWindowPlacement(hwnd, ref placement);

            size = new Size(placement.rcNormalPosition.Right - (placement.rcNormalPosition.Left * 2), placement.rcNormalPosition.Bottom - (placement.rcNormalPosition.Top * 2));
            point = new Point(placement.rcNormalPosition.Left, placement.rcNormalPosition.Top);
        }

        private void Delay(int ms)
        {
            DateTime dateTimeNow = DateTime.Now;
            TimeSpan duration = new TimeSpan(0, 0, 0, 0, ms);
            DateTime dateTimeAdd = dateTimeNow.Add(duration);
            while (dateTimeAdd >= dateTimeNow)
            {
                Application.DoEvents();
                dateTimeNow = DateTime.Now;
            }
            return;
        }

    }
}