让窗体获得焦点,一定会有您用到的时候

开发环境:Visual Studio .NET 2005 下的Windows Form Application

 

应用场景: 当我们有个窗体中的数据发生了变化而此窗体又没有获得焦点(不是用户操作的当前窗口)的时候,我们希望它获得焦点,这样用户就可以立刻发现它上面的数据发生了变化。

 

新建一个Window应用程序,会建立Form1,再添加一个Timer(timer1),设置如下属性:

 

 

然后添加timer1的Tick事件函数,完整代码如下:

 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

 

namespace Test

{
    public partial class PlayVoice : Form
    {
        public PlayVoice()
        {
            InitializeComponent();
        }


        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "GetForegroundWindow", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
        public static extern IntPtr GetF();             //获得本窗体的句柄
        [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern bool SetF(IntPtr hWnd);    //设置此窗体为活动窗体

 

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (this.Handle != GetF())           //如果本窗口没有获得焦点
                SetF(this.Handle);                //设置本窗口获得焦点
        }
    }
}

 

运行看看,你会发现当Tick事件发生时,本窗口总会跳出来告诉你--我获得焦点了

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值