using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using PTMedicalInsurance.Forms;

namespace PTMedicalInsurance.Business
{
    public class PasswordKeyboardTrigger
    {

        // 启动监控线程
        public static void Start()
        {
            Thread monitorThread = new Thread(MonitorEditBox);
            monitorThread.IsBackground = true;
            monitorThread.Start();
        }

        // 监控编辑框状态
        private static void MonitorEditBox()
        {
            while (true)
            {
                IntPtr targetWindow = FindWindow(null, "安全控件 V1.0.6"); // 替换为目标窗体的标题
                if (targetWindow != IntPtr.Zero)
                {
                    IntPtr editBox = FindWindowEx(targetWindow, IntPtr.Zero, "Edit", null); // 查找编辑框
                    if (editBox != IntPtr.Zero)
                    {
                        // 检查编辑框是否获得焦点
                        IntPtr focusedWindow = GetFocus();
                        if (focusedWindow == editBox)
                        {
                            // 显示密码键盘
                            Invoke((MethodInvoker)delegate
                            {
                                PasswordKeyboardForm passwordKeyboard = new PasswordKeyboardForm(editBox);
                                passwordKeyboard.ShowDialog();
                            });
                        }
                    }
                }
                Thread.Sleep(500); // 每500ms检查一次
            }
        }

        private static void Invoke(MethodInvoker methodInvoker)
        {
            throw new NotImplementedException();
        }

        // Windows API
        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr FindWindowEx(IntPtr parentHandle, IntPtr childAfter, string className, string windowTitle);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr GetFocus();
    }
}
