如果窗口在后台,如何允许按钮单击事件

时间:2019-01-21 16:24:57

标签: c# winforms events process

我有一个应用程序 ParentApp ,它将启动另一个应用程序 ChildApp

ParentApp会在ChildApp运行时显示表单-只是一种 Childapp当前正在运行显示,带有取消按钮,这会杀死ChildApp。 / p>

我希望ParentApp运行时ChildApp不可用,所以每当有人单击ParentApp时,我都想将ChildApp带到前台,这很好。

因此,我已将此事件处理程序添加到ParentApp中,该事件处理程序响应表单的Activated事件。

private void ParentAppForm_Activated(object sender, EventArgs e)
{
    IntPtr childHwnd = _childApp.MainWindowHandle;
    SetForegroundWindow(childHwnd );
}

({GotFocus似乎不起作用)

不幸的是,如果用户单击Cancel上的ParentAppForm按钮,则该按钮的事件处理程序将永远不会被点击,因为Activated事件首先被触发并将前景窗口设置为另一个过程。

这周围是否存在-即使应用程序不在前台,也可以触发按钮事件?

1 个答案:

答案 0 :(得分:1)

作为一种快速的解决方法,可以在激活表单时检查鼠标指针是否在 Button.Bounds 所描述的区域内。

您可以使用PointToClient坐标和Cursor.Position将鼠标指针位置转换为Form.Bounds坐标。

类似这样的东西:

private void ParentAppForm_Activated(object sender, EventArgs e)
{
    if (this.button1.Bounds.Contains(this.PointToClient(Cursor.Position)))
        ChildForm.Close();  //Or ChildApp.Kill()
    else
        ChildForm.BringToFront();  //Or SetForegroundWindow(ChildApp.Handle)
}