您的位置:首页 > 编程语言 > C#

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: