using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Diagnostics;


namespace US.Browser.IE.BLL
{
    /// <summary>
    /// 调用c++系统api区域
    /// </summary>
    public static class WindowHWND
    {

        [DllImport("urlmon.dll", CharSet = CharSet.Ansi)]
        public static extern int UrlMkSetSessionOption(int dwOption, string pBuffer, int dwBufferLength, int dwReserved);
        public const int URLMON_OPTION_USERAGENT = 0x10000001;

        //实现F12功能的初始化。下一版本再做，初始化时已经屏蔽
        [DllImport("SuperF12.dll", EntryPoint = "InitSuperF12")]
        public static extern void InitSuperF12();


        public const int GWL_EXSTYLE = -20;
        public const int WS_EX_TRANSPARENT = 0x00000020;
        public const int WS_EX_LAYERED = 0x00080000;

        /// <summary>
        /// 使窗口有鼠标穿透功能
        /// </summary>
        private static void CanPenetrate(IntPtr ui)
        {
            long intExTemp = GetWindowLong(ui, (int)GWL_EXSTYLE);
            int oldGWLEx = SetWindowLong(ui, GWL_EXSTYLE, WS_EX_TRANSPARENT | WS_EX_LAYERED);
        }

        #region 内存处理


        [DllImport("user32.dll", EntryPoint = "GetWindowThreadProcessId", SetLastError = true,
           CharSet = CharSet.Unicode, ExactSpelling = true,
           CallingConvention = CallingConvention.StdCall)]
        public static extern long GetWindowThreadProcessId(long hWnd, long lpdwProcessId);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern int SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        [DllImport("user32.dll", EntryPoint = "GetWindowLongA", SetLastError = true)]
        public static extern long GetWindowLong(IntPtr hwnd, int nIndex);

        [DllImport("user32.dll")]
        public static extern int SetWindowLong(IntPtr hwnd, int nIndex, int dwNewLong);

        public static IntPtr SetWindowLong(HandleRef hWnd, int nIndex, int dwNewLong)
        {
            if (IntPtr.Size == 4)
            {
                return SetWindowLongPtr32(hWnd, nIndex, dwNewLong);
            }
            return SetWindowLongPtr64(hWnd, nIndex, dwNewLong);
        }
        [DllImport("user32.dll", EntryPoint = "SetWindowLong", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr32(HandleRef hWnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr", CharSet = CharSet.Auto)]
        public static extern IntPtr SetWindowLongPtr64(HandleRef hWnd, int nIndex, int dwNewLong);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern long SetWindowPos(IntPtr hwnd, long hWndInsertAfter, long x, long y, long cx, long cy, long wFlags);

        [DllImport("user32.dll", SetLastError = true)]
        public static extern bool MoveWindow(IntPtr hwnd, int x, int y, int cx, int cy, bool repaint);

        [DllImport("user32.dll", EntryPoint = "PostMessageA", SetLastError = true)]
        public static extern bool PostMessage(IntPtr hwnd, uint Msg, uint wParam, uint lParam);

        /// <summary>
        /// 设置线程内存占用大小
        /// </summary>
        /// <param name="pProcess"></param>
        /// <param name="dwMinimumWorkingSetSize"></param>
        /// <param name="dwMaximumWorkingSetSize"></param>
        /// <returns></returns>
        //[DllImport("KERNEL32.DLL", EntryPoint = "SetProcessWorkingSetSize", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        //public static extern bool SetProcessWorkingSetSize(IntPtr pProcess, int dwMinimumWorkingSetSize, int dwMaximumWorkingSetSize);

        //[DllImport("KERNEL32.DLL", EntryPoint = "GetCurrentProcess", SetLastError = true, CallingConvention = CallingConvention.StdCall)]
        //public static extern IntPtr GetCurrentProcess();

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetProcessWorkingSetSize(IntPtr process, UIntPtr minimumWorkingSetSize, UIntPtr maximumWorkingSetSize);

        /// <summary>
        /// 释放内存
        /// </summary>
        public static void freem()
        {
            //SetProcessWorkingSetSize(Process.GetCurrentProcess().Handle, (UIntPtr)0xFFFFFFFF, (UIntPtr)0xFFFFFFFF);
            GC.Collect(GC.MaxGeneration); GC.WaitForPendingFinalizers(); GC.Collect();
        }

        #endregion

        #region 窗体使用

        public const int WM_ACTIVATE = 0x006;
        public const int WM_ACTIVATEAPP = 0x01C;
        public const int WM_NCACTIVATE = 0x086;
        public const int WA_INACTIVE = 0;
        public const int WM_MOUSEACTIVATE = 0x21;
        public const int MA_NOACTIVATE = 3;

        /// <summary>
        /// 显示窗体的方法
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="nCmdShow"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [DllImport("user32.dll ", SetLastError = true)]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        [DllImport("user32.dll", EntryPoint = "ShowWindow", CharSet = CharSet.Auto)]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);
        public const int SW_RESTORE = 9;
        public const int SW_SHOW = 5;
        [DllImport("User32.dll")]
        public static extern bool SetForegroundWindow(System.IntPtr hWnd);

        [DllImport("User32.dll")]
        public static extern bool ShowWindowAsync(System.IntPtr hWnd, int cmdShow);

        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern bool ShowWindow(HandleRef hWnd, int nCmdShow);

        /// <summary>
        /// 聚焦窗体使用
        /// </summary>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern IntPtr GetActiveWindow();//获得当前活动窗体
        [DllImport("user32.dll")]
        public static extern IntPtr SetActiveWindow(IntPtr hwnd);//设置活动窗体
        /// <summary>
        /// 活动窗体闪烁
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="bInvert"></param>
        /// <returns></returns>
        [DllImport("user32")]
        public static extern long FlashWindow(IntPtr hwnd, bool bInvert);

        /// <summary>
        /// 查找窗体
        /// </summary>
        /// <param name="lpClassName"></param>
        /// <param name="lpWindowName"></param>
        /// <returns></returns>
        [DllImport("user32.dll", EntryPoint = "GetWindow")]//获取窗体句柄，hwnd为源窗口句柄
        public static extern int GetWindow(int hwnd, int wCmd);
        [DllImport("user32.dll", EntryPoint = "SetParent")]//设置父窗体
        public static extern int SetParent(int hWndChild, int hWndNewParent);

        /*wCmd指定结果窗口与源窗口的关系，它们建立在下述常数基础上：
          GW_CHILD
          寻找源窗口的第一个子窗口
          GW_HWNDFIRST
          为一个源子窗口寻找第一个兄弟（同级）窗口，或寻找第一个顶级窗口
          GW_HWNDLAST
          为一个源子窗口寻找最后一个兄弟（同级）窗口，或寻找最后一个顶级窗口
          GW_HWNDNEXT
          为源窗口寻找下一个兄弟窗口
          GW_HWNDPREV
          为源窗口寻找前一个兄弟窗口
          GW_OWNER
          寻找窗口的所有者
         */

        #endregion

        #region 坐标使用

        [DllImport("user32.dll", EntryPoint = "GetCursorPos")]//获取鼠标坐标
        public static extern int GetCursorPos(ref POINTAPI lpPoint);

        [StructLayout(LayoutKind.Sequential)]//定义与API相兼容结构体，实际上是一种内存转换
        public struct POINTAPI { public int X; public int Y; }

        [DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//指定坐标处窗体句柄
        public static extern int WindowFromPoint(int xPoint, int yPoint);

        [DllImport("User32.dll")]
        public static extern IntPtr WindowFromPoint(System.Drawing.Point p);

        /// <summary>
        /// 获取鼠标的位置
        /// </summary>
        /// <returns></returns>
        public static POINTAPI GetCur()
        {
            POINTAPI point = new POINTAPI();//必须用与之相兼容的结构体，类也可以
            GetCursorPos(ref point);//获取当前鼠标坐标
            return point;
        }

        /// <summary>
        /// 根据坐标获取指定窗体的位置
        /// </summary>
        /// <returns></returns>
        public static IntPtr GetHWND()
        {
            POINTAPI point = new POINTAPI();//必须用与之相兼容的结构体，类也可以
            GetCursorPos(ref point);//获取当前鼠标坐标
            int hwnd = WindowFromPoint(point.X, point.Y);//获取指定坐标处窗口的句柄
            return (IntPtr)hwnd;
        }

        #endregion

        #region 窗体美化

        [DllImport("gdi32.dll")]
        public static extern int CreateRoundRectRgn(int x1, int y1, int x2, int y2, int x3, int y3);

        /// <summary>
        /// 圆角
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="hRgn"></param>
        /// <param name="bRedraw"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        public static extern int SetWindowRgn(IntPtr hwnd, int hRgn, Boolean bRedraw);

        [DllImport("gdi32.dll", EntryPoint = "DeleteObject", CharSet = CharSet.Ansi)]
        public static extern int DeleteObject(int hObject);


        const int CS_DropSHADOW = 0x20000;
        const int GCL_STYLE = (-26);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int SetClassLong(IntPtr hwnd, int nIndex, int dwNewLong);
        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        public static extern int GetClassLong(IntPtr hwnd, int nIndex);


        /// <summary>
        /// 添加圆角
        /// </summary>
        /// <param name="form"></param>
        /// <param name="rgnRadius"></param>
        public static void SetFormRoundRectRgn(Form form, int rgnRadius)
        {
            int hRgn = 0;
            hRgn = CreateRoundRectRgn(0, 0, form.Width + 1, form.Height + 1, rgnRadius, rgnRadius);
            SetWindowRgn(form.Handle, hRgn, true);
            DeleteObject(hRgn);
        }

        /// <summary>
        /// 添加阴影
        /// </summary>
        /// <param name="ui"></param>
        public static void SetFormShadow(IntPtr ui)
        {
            SetClassLong(ui, GCL_STYLE, GetClassLong(ui, GCL_STYLE) | CS_DropSHADOW); //API函数加载，实现窗体边框阴影效果
        }

        #endregion

        #region 动画

        /// <summary>
        /// 从左到右显示
        /// </summary>
        public const Int32 AW_HOR_POSITIVE = 0x00000001;
        /// <summary>
        /// 从右到左显示
        /// </summary>
        public const Int32 AW_HOR_NEGATIVE = 0x00000002;
        /// <summary>
        /// 从上到下显示
        /// </summary>
        public const Int32 AW_VER_POSITIVE = 0x00000004;
        /// <summary>
        /// 从下到上显示
        /// </summary>
        public const Int32 AW_VER_NEGATIVE = 0x00000008;
        /// <summary>
        /// 若使用了AW_HIDE标志，则使窗口向内重叠，即收缩窗口；否则使窗口向外扩展，即展开窗口
        /// </summary>
        public const Int32 AW_CENTER = 0x00000010;
        /// <summary>
        /// 隐藏窗口，缺省则显示窗口
        /// </summary>
        public const Int32 AW_HIDE = 0x00010000;
        /// <summary>
        /// 激活窗口。在使用了AW_HIDE标志后不能使用这个标志
        /// </summary>
        public const Int32 AW_ACTIVATE = 0x00020000;
        /// <summary>
        /// 使用滑动类型。缺省则为滚动动画类型。当使用AW_CENTER标志时，这个标志就被忽略
        /// </summary>
        public const Int32 AW_SLIDE = 0x00040000;
        /// <summary>
        /// 透明度从高到低
        /// </summary>
        public const Int32 AW_BLEND = 0x00080000;

        /// <summary>
        /// 执行动画
        /// </summary>
        /// <param name="whnd">控件句柄</param>
        /// <param name="dwtime">动画时间</param>
        /// <param name="dwflag">动画组合名称</param>
        /// <returns>bool值，动画是否成功</returns>
        [DllImport("user32")]
        public static extern bool AnimateWindow(IntPtr whnd, int dwtime, int dwflag);


        #endregion

        #region 窗体拖动

        //窗体拖动
        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();//API函数
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwdn, int wMsg, int mParam, int lParam);//接受发送来的消息 并处理
        public const int WM_SYSCOMMAND = 0x0112;//该变量表示将向Windows发送消息的类型
        public const int SC_MOVE = 0xF010;//该变量表示发送消息的附加消息
        public const int HTCAPTION = 0x0002;

        /// <summary>
        /// 拖动
        /// </summary>
        public static void _Main_Drag(Form UFE)
        {
            ReleaseCapture();//该函数从当前线程中释放鼠标捕获事件，并恢复鼠标输入处理
            SendMessage(UFE.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
        }

        #endregion

        #region 内存控制

        public static string GetSystemXX()
        {
            Process CurrentProcess = Process.GetCurrentProcess(); //制定进程
            return (CurrentProcess.WorkingSet64 / 1024 / 1024).ToString() + "M (" + (CurrentProcess.WorkingSet64 / 1024).ToString() + "KB)";


            //CurrentProcess.Id.ToString();//PID
            //((Double)(CurrentProcess.TotalProcessorTime.TotalMilliseconds - CurrentProcess.UserProcessorTime.TotalMilliseconds)).ToString();//CPU
            //(CurrentProcess.WorkingSet64 / 1024 / 1024).ToString() + "M (" + (CurrentProcess.WorkingSet64 / 1024).ToString() + "KB)";//占用内存
            //  CurrentProcess.Threads.Count.ToString();//线程
        }

        #region 使用值

        public const int GWL_STYLE = (-16);
        public const int WS_VISIBLE = 0x10000000;

        #endregion

        #endregion


        #region

        //[System.Runtime.InteropServices.DllImport("user32.dll")]
        //private const int WM_ACTIVATE = 0x006;
        //private const int WM_ACTIVATEAPP = 0x01C;
        //private const int WM_NCACTIVATE = 0x086;
        //private const int WA_INACTIVE = 0;
        //private const int WM_MOUSEACTIVATE = 0x21;
        //private const int MA_NOACTIVATE = 3;

        //protected override void WndProc(ref Message m)
        //{
        //    if (m.Msg == WM_MOUSEACTIVATE)
        //    {
        //        m.Result = new IntPtr(MA_NOACTIVATE);
        //        return;
        //    }
        //    else if (m.Msg == WM_NCACTIVATE)
        //    {
        //        if (((int)m.WParam & 0xFFFF) != WA_INACTIVE)
        //        {
        //            if (m.LParam != IntPtr.Zero)
        //            {
        //                SetActiveWindow(m.LParam);
        //            }
        //            else
        //            {
        //                SetActiveWindow(IntPtr.Zero);
        //            }
        //        }
        //    }
        //    base.WndProc(ref m);
        //}

        #endregion
    }
}
