现在的位置: 首页 > 综合 > 正文

WPF 设置windows窗体在最前端 top window / Foreground Window

2012年09月23日 ⁄ 综合 ⁄ 共 856字 ⁄ 字号 评论关闭

需要实现的功能是当鼠标滑过WPF窗体的textbox时,获取textbox的输入焦点。

步骤:

1.需要把此WPF的Topmost属性设置成true。

2.引用 win32 API 函数:

View Code
        [DllImport("user32.dll")]
        
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);

            bool b = SetForegroundWindow(handle);
            System.Threading.Thread.Sleep(
100);
  
            tbWord.Focus();
            tbWord.SelectAll();
        }

 程序演示: http://www.cnblogs.com/JimmyXiao/archive/2011/03/17/1987561.html

 

抱歉!评论已关闭.