简体   繁体   English

如何在特定时间使用C#隐藏和显示表单?

[英]How do I hide and show form at a specific time in C#?

I am writing a small application for reminders. 我正在编写一个用于提醒的小应用程序。 For this, I got great help from a similar question and answer on Stack Overflow. 为此,我从Stack Overflow的类似问答中获得了很大的帮助。 I used the code mentioned by Thunder from here . 从这里开始使用Thunder提到的代码。

The relevant code is: 相关代码为:

private void Form1_Load(object sender, EventArgs e)
    {
        System.Threading.TimerCallback callback = new            System.Threading.TimerCallback(ProcessTimerEvent);
        var dt =    new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day   , 10, 0, 0);

        if (DateTime.Now < dt)
        {
            var timer = new System.Threading.Timer(callback, null, dt - DateTime.Now, TimeSpan.FromHours(24));
        this.Hide(); // This line works... Form hides itself
        }

    }

    private void ProcessTimerEvent(object obj)
    {
        //MessageBox.Show("Hi Its Time");
        this.Show();  //This line does not work. Form gets disposed off instead of show
    }

My problem: I get everything as mentioned in that answer (including MessageBox). 我的问题:我得到了该答案中提到的所有内容(包括MessageBox)。 However, if I try to hide the form when a callback is made and show it once again instead of MessageBox.Show("Hi Its Time") it does not work. 但是,如果我尝试在进行回调时隐藏表单,然后再次显示它而不是MessageBox.Show("Hi Its Time")则它将不起作用。 See my comments on each line. 看到我在每一行的评论。 I don't understand why the form gets disposed. 我不明白为什么要处理表格。

this.Visible() // does not work and disposed off the same way

Also tried to move the form out of screen by changing its location property. 还尝试通过更改表单的location属性将其移出屏幕。 On return, bring back to its original location but this also does not work. 返回时,请返回其原始位置,但这也不起作用。 What can I do to hide & show the form on return ? 我该怎么做才能隐藏并显示退货表格?

I believe you're having a cross thread issue. 我相信您遇到了跨线程问题。 Your callback should look like this: 您的回调应如下所示:

private void ProcessTimerEvent(object obj)
{
    if (this.InvokeRequired)
    {
        this.Invoke(new Action<object>(this.ProcessTimerEvent), obj);
    }
    else
    {
         this.Show();
    }
}

I just checked and found that your code is getting this error: 我刚刚检查发现您的代码正在收到此错误:

Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on. 跨线程操作无效:控件“ Form1”从创建该线程的线程之外的线程访问。

You just have to change ProcessTimerEvent function to this: 您只需要将ProcessTimerEvent函数更改为此:

if (this.InvokeRequired)
{
    this.BeginInvoke(new Action<object>(ProcessTimerEvent), obj);

    // To wait for the thread to complete before continuing.
    this.Invoke(new Action<object>(ProcessTimerEvent), obj);
}
else
{
    this.Show();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM