• 当前进程/活动窗体的句柄


    1、当前进程的句柄:

    先引用WIN32 API:

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern IntPtr GetModuleHandle(string lpModuleName);

    获取当前进程模块的名称:

    string moduleName=Process.GetCurrentProcess().MainModule.ModuleName------这里需要引用命名空间:System.Diagnostics;

    调用函数获取句柄:IntPtr hwnd=GetModuleHandle(moduleName)

    2、当前活动(获得焦点)的窗体

    先引用命名空间:
    System.Runtime.InteropServices;

    引用WIN32 API:

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    public static extern IntPtr GetForegroundWindow();----返回值类型是IntPtr,即为当前获得焦点窗口的句柄

    获取当前激活窗口的句柄:IntPtr hwnd=GetForegroundWindow();

    PS:GetActiveWindow 只是获取当前程序中(严格地说是线程中)被激活的窗口;
    GetForegroundWindow 是获取当前系统中被激活的窗口.

    两个函数的级别不一样, 一个是线程级、一个是系统级.

    被激活的窗口不一定是顶层窗口(最上面的窗口).

    获取到该窗口句柄后,可以对该窗口进行操作.如,关闭该窗口或在该窗口隐藏后,使其显示


    同样引用WIN32 API:


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

    其中ShowWindow(IntPtr hwnd, int nCmdShow);

    nCmdShow的含义

    0    关闭窗口
    1    正常大小显示窗口
    2    最小化窗口
    3    最大化窗口

    使用实例:    ShowWindow(myPtr, 0);

    获取窗口大小及位置:需要调用方法GetWindowRect(IntPtr hWnd, ref RECT lpRect)

            [DllImport("user32.dll")]
            [return: MarshalAs(UnmanagedType.Bool)]
            static extern bool GetWindowRect(IntPtr hWnd, ref RECT lpRect);

            [StructLayout(LayoutKind.Sequential)]
            public struct RECT
            {
                public int Left;                             //最左坐标
                public int Top;                             //最上坐标
                public int Right;                           //最右坐标
                public int Bottom;                        //最下坐标
            }

    System.Runtime.InteropServicesSystem.Runtime.InteropServices

    示例:

                 InPtr awin = GetForegroundWindow();    //获取当前窗口句柄
                 RECT rect = new RECT();
                 GetWindowRect(awin, ref rect);
                 int width = rc.Right - rc.Left;                        //窗口的宽度
                 int height = rc.Bottom - rc.Top;                   //窗口的高度
                 int x = rc.Left;                                              
                 int y = rc.Top;

  • 相关阅读:
    Jmeter在命令行运行技巧
    Tomcat6 一些调优设置内存和连接数
    用例结构优化心得
    LoadRunner 调用dll方法
    DLL接口自动化测试总结
    Loadrunner进行md5加密方法
    Loadrunner检查点使用总结
    网络上可供测试的Web Service
    04 json,xml混合封装通信
    03 xml封装通信接口
  • 原文地址:https://www.cnblogs.com/xiesong/p/6676860.html
Copyright © 2020-2023  润新知