C#怎样获得窗口句柄?

C#怎样获得窗口句柄?,第1张

一个网上的例子

c# 获取鼠标处窗口句柄,程序嵌入桌面

using System

using System.Collections.Generic

using System.ComponentModel

using System.Data

using System.Drawing

using System.Text

using System.Windows.Forms

using System.Runtime.InteropServices

namespace WindowsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent()

}

[DllImport("user32.dll", EntryPoint = "FindWindow")]

public static extern int FindWindow(

string lpClassName,

string lpWindowName

)

[DllImport("user32.dll", EntryPoint = "GetWindow")]//获取窗体句柄,hwnd为源窗口句柄

/*wCmd指定结果窗口与源窗口的关系,它们建立在下述常数基础上:

GW_CHILD

寻找源窗口的第一个子窗口

GW_HWNDFIRST

为一个源子窗口寻找第一个兄弟(同级)窗口,或寻找第一个顶级窗口

GW_HWNDLAST

为一个源子窗口寻找最后一个兄弟(同级)窗口,或寻找最后一个顶级窗口

GW_HWNDNEXT

为源窗口寻找下一个兄弟窗口

GW_HWNDPREV

为源窗口寻找前一个兄弟窗口

GW_OWNER

寻找窗口的所有者

*/

public static extern int GetWindow(

int hwnd,

int wCmd

)

[DllImport("user32.dll", EntryPoint = "SetParent")]//设置父窗体

public static extern int SetParent(

int hWndChild,

int hWndNewParent

)

[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

)

private void timer1_Tick(object sender, EventArgs e)

{

POINTAPI point = new POINTAPI()//必须用与之相兼容的结构体,类也可以

GetCursorPos(ref point)//获取当前鼠标坐标

int hwnd = WindowFromPoint(point.X, point.Y)//获取指定坐标处窗口的句柄

this.label1.Text =point.X.ToString() + ":" + point.Y.ToString() + "-" + hwnd.ToString()//显示效果,此时窗口已经嵌入桌面了

}

const int GW_CHILD = 5//定义窗体关系

private void Form1_Load(object sender, EventArgs e)

{

int hDesktop = FindWindow("Progman", null)//获取系统句柄

hDesktop = GetWindow(hDesktop, GW_CHILD)//获取其子窗口句柄,就是桌面的句柄

SetParent((int)this.Handle, hDesktop)//设置父窗体,第一个为要被设置的窗口,第二个参数为指定其父窗口句柄

}

}

}

1、启动VS,新建C# WinForm项目。

2、在Form1中添加4个Label控件,并布局如下。

3、在Form1中添加代码,如下。

4、完成之后,调试运行,结果如下。

注意事项:

C++不仅拥有计算机高效运行的实用性特征,同时还致力于提高大规模程序的编程质量与程序设计语言的问题描述能力。

思路有问题,应该如下做(只限于有标题栏的窗口)

1.找到窗口,通过标题,如下:

HWND

myHwnd

/////////找到窗口的HDR

myHwnd=::FindWindow(

NULL,/*

class

name*/

"窗口名称"

//LPCTSTR

lpWindowName

//

window

name

)

if(myHwnd==NULL)

//"Cannot

Find")

2

//找到窗口的位置及大小

::GetWindowRect(

myHwnd,

//

handle

to

window

mRect

//

client

coordinates

)

3.获得屏幕句柄

HDC

hdc

=

::GetDC(NULL)

4.通过mRect

和hdc

对界面进行 *** 作


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/11145130.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-13
下一篇2023-05-13

发表评论

登录后才能评论

评论列表(0条)

    保存