日期:2014-05-18  浏览次数:20754 次

在C#中怎样让窗体一直占有焦点?
我想把一个窗体放在最前面,不关掉这个窗体,就切换不到别的程序上,怎么设置呢?用C#语言,先谢了。

------解决方案--------------------
C# code
using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace Class1
{
    /// <summary>
    /// WinAPI 的摘要说明。
    /// </summary>
    public class SetWindow
    {
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern IntPtr GetForegroundWindow();   //WINAPI 获取当前活动窗体的句柄
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        private static extern bool SetForegroundWindow(IntPtr hWnd);   //WINAPI 设置当前活动窗体的句柄



        private Thread Th;
        private IntPtr MainInt; 
        
        public SetWindow(IntPtr MainIntPrt)
        {            
            MainInt=MainIntPrt;              
        }
        /// <summary>
        /// 开始线程
        /// </summary>
        public void Star()
        {            
            Th=new Thread(new ThreadStart(SetForm)); 
            Th.Start();
        }        
        private void SetForm()
        {
            while(true)  
            {
                if(MainInt!=GetForegroundWindow())SetForegroundWindow(MainInt);                
                
                Thread.Sleep(1);  
            }
        }
        /// <summary>
        /// 关闭线程
        /// </summary>
        public void Close()
        {
            Th.Abort();  
        }
    }
}