如何自动最小化我的Windows窗体应用程序(C#)?

时间:2016-07-17 10:11:29

标签: c# visual-studio

我正在创建一个基本的Windows窗体应用程序。如果我运行我的项目(程序启动),如何将表单设置为在用户不与我的表单交互时自动最小化?

例如,当您全屏观看某些YouTube视频时,它会显示条形播放器,当用户不在播放器内移动或移动任何内容时,条形播放器将自动隐藏。

那么,我怎样才能创建类似这样的东西呢?它是如何做到的?

3 个答案:

答案 0 :(得分:0)

您可以定义一个计时器,例如在15秒后调用您的隐藏操作。然后,将MouseMove,MouseClick和KeyPressed的事件处理程序附加到表单。每次发生此类事件时,它都会重置您的计时器。

答案 1 :(得分:0)

这是一个简单的例子。

您可以将From by set property WindowState最小化为FormWindowState.Minimized

处理Form最小化使用Timer时的时间。 On Tick事件将Timer的当前时间与您定义的时间进行比较。在用户中断(输入事件为MouseMove,MouseClick,KeyPress,或者您可以只选择其中一些)时,将时间重置为0.

public partial class Form1 : Form
{

    System.Windows.Forms.Timer timer;
    int milliseconds;
    const int TIME_TO_MINIMIZE = 1000;

    public Form1()
    {
        InitializeComponent();

        this.MouseMove += new MouseEventHandler(InputAction);
        this.MouseClick += new MouseEventHandler(InputAction);
        this.KeyPress += new KeyPressEventHandler(InputAction);

        milliseconds = 0;

        timer = new System.Windows.Forms.Timer();
        timer.Interval = 100;
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }

    private void timer_Tick(object sender, EventArgs e)
    {
        milliseconds += 100;
        if (milliseconds >= TIME_TO_MINIMIZE)
        {
            this.WindowState = FormWindowState.Minimized;
            milliseconds = 0;
        }
    }

    private void InputAction(object sender, EventArgs e)
    {
        milliseconds = 0;
    }
}

答案 2 :(得分:0)

您可以通过以下方式执行此操作:

public partial class frmTimer : Form
{
    System.Windows.Forms.Timer timer;

    public frmTimer()
    {
        InitializeComponent();

        timer = new Timer();
        timer.Enabled = true;
        timer.Interval = 10 * 1000;
        timer.Tick += Timer_Tick;
        timer.Start();

        // attach your events on which you want to reset your events
        this.MouseMove += FrmTimer_MouseMove;
        this.MouseDown += FrmTimer_MouseDown;
        this.KeyDown += FrmTimer_KeyDown;
    }

    private void FrmTimer_KeyDown(object sender, KeyEventArgs e)
    {
        timer.Stop();
        timer.Start();
    }

    private void FrmTimer_MouseDown(object sender, MouseEventArgs e)
    {
        timer.Stop();
        timer.Start();
    }

    private void FrmTimer_MouseMove(object sender, MouseEventArgs e)
    {
        timer.Stop();
        timer.Start();
    }

    private void Timer_Tick(object sender, EventArgs e)
    {
        if (this.WindowState != FormWindowState.Minimized)
            this.WindowState = FormWindowState.Minimized;
    }

}

我希望这会对你有所帮助。 :)