C#获取窗口句柄概念和方法实例
2016-02-21 00:30
711 查看
在Windows中,句柄是一个系统内部数据结构的引用。例如当你操作一个窗口,或说是一个Delphi窗体时,系统会给你一个该窗口的句柄,系统会通知你:你正在操作142号窗口,就此你的应用程序就能要求系统对142号窗口进行操作——移动窗口、改变窗口大小、把窗口极小化为图标等。实际上许多 Windows API函数把句柄作为它的第一个参数,如GDI(图形设备接口)句柄、菜单句柄、实例句柄、位图句柄等,不仅仅局限于窗口函数。换句话说,句柄是一种内部代码,通过它能引用受系统控制的特殊元素,如窗口、位图、图标、内存块、光标、字体、菜单等。
Private Declare Function GetWindowLong Lib "user32" Alias "GetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long) As Long Private Declare Function SetWindowLong Lib "user32" Alias "SetWindowLongA" (ByVal hwnd As Long, ByVal nIndex As Long, ByVal dwNewLong As Long) As Long Private Declare Function SetLayeredWindowAttributes Lib "user32" (ByVal hwnd As Long, ByVal crKey As Long, ByVal bAlpha As Byte, ByVal dwFlags As Long) As Long Private Const WS_EX_LAYERED = &H80000 Private Const GWL_EXSTYLE = (-20) Private Const LWA_ALPHA = &H2 Private Sub Form_Activate() On Error Resume Next For i = 0 To 150 Step 2.5 SetLayeredWindowAttributes Me.hwnd, 0, i, LWA_ALPHA DoEvents Next i End Sub Private Sub Form_load() Dim rtn As Long rtn = GetWindowLong(Me.hwnd, GWL_EXSTYLE) rtn = rtn Or WS_EX_LAYERED SetWindowLong Me.hwnd, GWL_EXSTYLE, rtn SetLayeredWindowAttributes Me.hwnd, 0, 0, LWA_ALPHA End Sub
//获取窗口标题 [DllImport("user32", SetLastError = true)] public static extern int GetWindowText( IntPtr hWnd,//窗口句柄 StringBuilder lpString,//标题 int nMaxCount //最大值 ); //获取类的名字 [DllImport("user32.dll")] private static extern int GetClassName( IntPtr hWnd,//句柄 StringBuilder lpString, //类名 int nMaxCount //最大值 ); //根据坐标获取窗口句柄 [DllImport("user32")] private static extern IntPtr WindowFromPoint( Point Point //坐标 ); private void timer1_Tick(object sender, EventArgs e) { int x = Cursor.Position.X; int y = Cursor.Position.Y; Point p = new Point(x, y); IntPtr formHandle = WindowFromPoint(p);//得到窗口句柄 StringBuilder title = new StringBuilder(256); GetWindowText(formHandle, title, title.Capacity);//得到窗口的标题 StringBuilder className = new StringBuilder(256); GetClassName(formHandle, className, className.Capacity);//得到窗口的句柄 this.textBox1.Text = title.ToString(); this.textBox2.Text = formHandle.ToString(); this.textBox3.Text = className.ToString(); }
相关文章推荐
- 【C#】基础知识—初识C#与.Net
- C#里氏转换/is/as
- c#委托与事件(详解)
- 一个C#语法高亮插件
- C# 多线程 lock 实例
- C#调用CMD程序
- C#中毫米与像素的换算方法
- C#中using与添加引用的区别
- C# thread类
- C#继承/this/base/new
- C#中Math.Round()实现中国式四舍五入
- C# Random 生成不重复随机数
- 【C#学习之辨析小总结】
- C#之日志
- C#学习——字符串
- c# 扩展方法 奇思妙想 推荐酷。
- StructLayout特性
- 关于C#托管代码与非托管代码的理解
- (转)C#程序开发中经常遇到的10条实用的代码
- C# WPF获取任务栏时间区域的Rectangle