zoukankan      html  css  js  c++  java
  • c#实现Form窗体始终在桌面最前端显示

    方法一:

    //调用API
    
    [System.Runtime.InteropServices.DllImport("user32", CharSet = System.Runtime.InteropServices.CharSet.Auto, ExactSpelling = true)]
    
    public static extern IntPtr GetFocus(); //获得本窗体的句柄
    
    [System.Runtime.InteropServices.DllImport("user32", EntryPoint = "SetForegroundWindow")]
    
    public static extern bool SetFocus(IntPtr hWnd);//设置此窗体为活动窗体
    
    
    // 定义变量,句柄类型
    
    public IntPtr han;
    
    private void Form1_Load(object sender, EventArgs e){
    
    //在窗体加载的时候给变量赋值,即将当前窗体的句柄赋给变量
    
    han = this.Handle;
    
    }
    private void timer1_Tick(object sender, EventArgs e){
    
    // 加载一个定时器控件,验证当前WINDOWS句柄是否和本窗体的句柄一样,如果不一样,则激活本窗体
    
    if (han != GetFocus()){
    
    SetFocus(han);
    
    }
    
    this.WindowState = FormWindowState.Normal;
    
    }

    c#本来就有Focus()方法,我没用DllImport,试过下面几个方法都不行

    control.Activate();
    control.TopMost = true;
    control.Focus();

    方法二:

    [System.Runtime.InteropServices.DllImport("user32")]
    private static extern IntPtr GetActiveWindow();//获取当前窗体的活动状态
    
    // 判断当前窗口是否处于活动状态的方法
    
    private bool ThisIsActive(){ return (GetActiveWindow() == this.Handle);}
    
    private void timer1_Tick(object sender, EventArgs e){
    
    if (!ThisIsActive()){
    
    this.Activate();
    
    }
    
    this.WindowState = FormWindowState.Normal;
    
    }

    方法三:

    [DllImport("user32")]    
    private    static    extern    IntPtr    FindWindow(string    lpClassName,string    lpWindowName);    
         
    [DllImport("user32")]    
    private    static    extern    IntPtr    SetParent(IntPtr    hWndChild,    IntPtr    hWndNewParent);    
         
    //在窗体On_Load事件中添加(Santos的代码):    
    IntPtr    hDeskTop=FindWindow("Progman",    "Program    Manager");    
    SetParent(this.Handle,hDeskTop);

    方法四:

    [System.Runtime.InteropServices.DllImport("user32.dll")]
    static extern bool SetForegroundWindow(IntPtr hWnd);

    拓展:

    private void Form1_Load(object sender, EventArgs e)
    {
        this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
    
        this.ShowInTaskbar = false;
        this.TopMost = true;
        this.timer1.Interval = 1;
        this.timer1.Enabled = true;
        this.WindowState = FormWindowState.Maximized;
    }
    
    private void timer1_Tick(object sender, EventArgs e)
    {
        SetForegroundWindow(this.Handle);
    }
  • 相关阅读:
    Django 两张表的正向查找和反向查找
    表结构基类写法
    vue绑定用户页面--新浪
    新浪微博绑定用户接口
    vue新浪微博回调空页面
    新浪微博回调接口
    vue获取授权url
    Android AsyncTask完全解析,带你从源码的角度彻底理解
    Android 3D滑动菜单完全解析,实现推拉门式的立体特效
    Android中轴旋转特效实现,制作别样的图片浏览器
  • 原文地址:https://www.cnblogs.com/code1992/p/13556509.html
Copyright © 2011-2022 走看看