winform操作windows系统计算器

86206132 2019-11-04

winform对系统计算器的调用,启动,最大化最小化显示,在mainwindow设置topmost=true时,正常显示计算器并置顶。

/// <summary>
        /// 获取窗体的句柄函数
        /// </summary>
        /// <param name="lpClassName">窗口类名</param>
        /// <param name="lpWindowName">窗口标题名</param>
        /// <returns>返回句柄</returns>
        [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)]
        public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

        /// <summary>
        /// 窗体的显示控制
        /// </summary>
        /// <param name="hWnd">句柄</param>
        /// <param name="nCmdShow">
        /// HIDE = 0
        /// NORMAL = 1
        /// MAXIMIZE = 3
        /// SHOWNOACTIVATE = 4
        /// SHOW = 5
        /// MINIMIZE = 6
        /// RESTORE = 9
        /// SHOWDEFAULT = 10</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd,int nCmdShow);

        /// <summary>
        /// 更改子窗口,弹出窗口或顶级窗口的大小,位置和Z顺序。这些窗口是根据其在屏幕上的外观排序的。最顶部的窗口获得最高排名,并且是Z顺序中的第一个窗口。
        /// </summary>
        /// <param name="hWnd">窗口的句柄</param>
        /// <param name="hWndlnsertAfter">在Z顺序中位于定位的窗口之前的窗口的句柄  0; 在前面 1; 在后面 -1; 在前面, 位于任何顶部窗口的前面 -2; 在前面, 位于其他顶部窗口的后面</param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        /// <param name="cx"></param>
        /// <param name="cy"></param>
        /// <param name="Flags">窗口尺寸和定位的标志</param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndlnsertAfter, int X, int Y, int cx, int cy, uint Flags);

            //启动计算器
            public void start_Calc()
            {
                AppLog.Info($"start calc ...");

                // 获取查找窗体句柄(通过窗体标题名)
                IntPtr calcHandle = FindWindow(null, "计算器");
                if (calcHandle == IntPtr.Zero)
                {
                    AppLog.Info($"pre start calc ...");
                    pcalc = Process.Start("calc.exe");
                    Thread.Sleep(800);
                    calcHandle = FindWindow(null, "计算器");
                }
                
                //将计算器显示为正常状态
                bool resultSetWindowState = ShowWindowAsync(calcHandle, 1);
                AppLog.Info($"set calc window status:{resultSetWindowState}");

                //将计算器显示在最上层
                bool result = SetWindowPos(calcHandle, new IntPtr(-1), 0, 0, 0, 0, 1 | 2);
                AppLog.Info($"set calc status:{result}");
            }

相关推荐