需要实现的功能是当鼠标滑过WPF窗体的textbox时,获取textbox的输入焦点。
步骤:
1.需要把此WPF的Topmost属性设置成true。
2.引用 win32 API 函数:
View Code
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
private static extern IntPtr SetFocus(IntPtr hWnd);
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport(
"user32.dll")]private static extern IntPtr SetFocus(IntPtr hWnd);
2.添加Textbox的MouseEnter事件
View Code
private void tbWord_MouseEnter(object sender, MouseEventArgs e)
{
HwndSource source = (HwndSource)PresentationSource.FromVisual(this);
IntPtr handle = source.Handle;
bool b1 = BringWindowToTop(handle);
System.Threading.Thread.Sleep(300);
System.Threading.Thread.Sleep(100);
tbWord.Focus();
tbWord.SelectAll();
}
{
HwndSource source = (HwndSource)PresentationSource.FromVisual(this);
IntPtr handle = source.Handle;
bool b1 = BringWindowToTop(handle);
System.Threading.Thread.Sleep(300);
bool b = SetForegroundWindow(handle);
System.Threading.Thread.Sleep(100);
tbWord.Focus();
tbWord.SelectAll();
}
程序演示: http://www.cnblogs.com/JimmyXiao/archive/2011/03/17/1987561.html