namespace HistoryView.Helper;

public static class SetWindow
{
    private static IntPtr intPtr;         //第三方应用窗口的句柄

    public static void ResizeWindow()
    {
        _ = ShowWindow(intPtr, 0);  //先将窗口隐藏
        _ = ShowWindow(intPtr, 3);  //再将窗口最大化，可以让第三方窗口自适应容器的大小
    }

    public static bool FindWindow(string formName)
    {
        intPtr = FindWindow(null!, formName);
        return intPtr != IntPtr.Zero;
    }

    public static void Clear()
    {
        _ = ShowWindow(intPtr, 0);
    }

    public static void ExitParent()
    {
        _ = ShowWindow(intPtr, 0);
        SetParent(IntPtr.Zero);
        _ = ShowWindow(intPtr, 9);
    }

    public static void SetParent(IntPtr hWndNewParent)
    {
        _ = ShowWindow(intPtr, 0);                 //先将窗体隐藏，防止出现闪烁
        _ = SetParent(intPtr, hWndNewParent);      //将第三方窗体嵌入父容器                    
        Thread.Sleep(100);                      //略加延时
        _ = ShowWindow(intPtr, 3);                 //让第三方窗体在容器中最大化显示
        //RemoveWindowTitle(intPtr);             // 去除窗体标题
        ResizeWindow();
    }


    //private static void RemoveWindowTitle(IntPtr vHandle)
    //{
    //    long style = GetWindowLong(vHandle, -16);
    //    style &= ~0x00C00000;
    //    SetWindowLong(vHandle, -16, style);
    //}

    [DllImport("user32.dll ", EntryPoint = "SetParent")]
    private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);   //将外部窗体嵌入程序

    [DllImport("user32.dll")]
    public static extern IntPtr FindWindow(string lpszClass, string lpszWindow);      //按照窗体类名或窗体标题查找窗体

    [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
    private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);                  //设置窗体属性

    [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
    public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, long dwNewLong);

    [DllImport("user32.dll", EntryPoint = "GetWindowLong", CharSet = CharSet.Auto)]
    public static extern long GetWindowLong(IntPtr hWnd, int nIndex);
}