计时器检查Winform最高启用

时间:2019-04-15 16:04:50

标签: c# winforms

我如何使循环计时器检查主窗体topmost.enable是否为false,直到标签可见,然后在标签无效时设置为true?

如果尝试了此代码但不起作用:

 private void InitializeAlive()
    {
        alive = new System.Timers.Timer();
        alive.Interval = 1000;
        alive.AutoReset = true;
        alive.Elapsed += Alive_Tick;
        alive.Start();
    }

    private void Alive_Tick(object sender, EventArgs e)
    {
        if (lblPassword.Enabled)
        {                
            this.TopMost = false;
        }
        else
        {
            this.TopMost = true;
            alive.Dispose();
        }
    }

    private void btnPrint_Click(object sender, EventArgs e)
    {
        if (txtPassword.Text == pswd)
        {
            TopMost = false;
            webPrintSetting.ShowPageSetupDialog();
            InitializeAlive();
        }
        else
        {
            btnPrint.Enabled = false;
            btnPrint.Visible = false;
            lblPassword.Visible = false;
            txtPassword.Enabled = false;
            txtPassword.Visible = false;
            txtPassword.Clear();
        }
    }

2 个答案:

答案 0 :(得分:1)

如果仅在标签的“启用”属性更改时需要执行某些操作,则只需将处理程序添加到“ EnabledChanged”属性,如下所示:

public Form1()
{
    InitializeComponent();

    lblPassword.EnabledChanged += new System.EventHandler(this.LblPassword_EnabledChanged);
}

并像这样实现处理程序:

private void LblPassword_EnabledChanged(object sender, EventArgs e)
{
    TopMost = !lblPassword.Enabled;
}

答案 1 :(得分:0)

我找到了一种方法,可以在最上面打开/关闭(直到目标进程正在运行为止)。

private Timer check;

public MyForm()
{
InitializeCheck();
}

private void InitializeCheck()
{
check = new Timer();
check.Interval = 5000;
check.Tick += Check_Tick;
check.Enabled = false;
}

private void Check_Tick(object sender, EventArgs e)
{
CheckProgram();
}

private void CheckProgram()
{
Process[] program = rocess.GetProcessesByName("notepad");
if (program.Length == 0)
{
check.Enabled = false;
TopMost = true;
}

private void button1_Click(object sender, EventArgs e)
{
TopMost = false;
check.Enabled = true;
}