今天,在学习WindowsApi时,发现了几个比较有趣的API,通过使用这几个API可以完成类似与桌面取词的功能!
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
public static extern int SetWindowPos(
int hwnd, //用于设置的窗体的句柄
int hWndInsertAfter,//用于对窗体最前端的操作(查手册获取相应的参数常量)
int x,//窗体的坐标x
int y,//窗体的坐标y
int cx,//窗体的长
int cy,//窗体的宽
int wFlags //对窗体的操作(查手册获取相应的参数常量)
);
用于实现将窗体至于最前面,这个要比C#自带的那个功能还要强大,可以让窗体至于,任务栏的最前面!
const int HWND_TOPMOST = -1;
const int SWP_SHOWWINDOW = 0x40;
/************************************************************************************/
[DllImport("user32.dll", EntryPoint = "GetWindowText")]
public static extern int GetWindowText(
int hwnd,//句柄
StringBuilder lpString,
int cch
);
获取当前句柄上的文字
注:只是用于一些存在句柄的控件或窗体,但是不是所有的控件都能获取的(例如:选项卡上的标签上的文字就无法获取)
/************************************************************************************/
[DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//获取当前点下的窗体或控件的句柄
public static extern int WindowFromPoint(
int xPoint,
int yPoint
);
/*************************************************************************************/
[DllImport("user32.dll", EntryPoint = "GetWindowTextLength")]//获取当前句柄中的文字长度
public static extern int GetWindowTextLength(
int hwnd
);
/*************************************************************************************/
UI层的控件:一个timer控件(用于实时获取当前的鼠标的在整个屏幕的位置),
一个label控件(用于现实当前控件或者窗体上的文字)
步骤:在窗体load时,让timer控件开始执行
注意:请重点理解红色标注的代码行
Demo:
[DllImport("user32.dll", EntryPoint = "GetWindowText")]
public static extern int GetWindowText(
int hwnd,//句柄
StringBuilder lpString,
int cch
);
[DllImport("user32.dll", EntryPoint = "WindowFromPoint")]//获取当前点下的窗体或控件的句柄
public static extern int WindowFromPoint(
int xPoint,
int yPoint
);
[DllImport("user32.dll", EntryPoint = "GetWindowTextLength")]//获取当前句柄中的文字长度
public static extern int GetWindowTextLength(
int hwnd
);
private void timer1_Tick(object sender, EventArgs e)
{
int windowsHandle = WindowFromPoint(Cursor.Position.X, Cursor.Position.Y);
int infoLength = GetWindowTextLength(windowsHandle);
StringBuilder text = new StringBuilder(infoLength+2);
GetWindowText(windowsHandle, text, infoLength + 2);
this.label1.Text = text.ToString();
}
联系客服