【问题标题】:Alert / Warning window won't pop up at control location警报/警告窗口不会在控制位置弹出
【发布时间】:2015-08-11 23:37:47
【问题描述】:

我正在尝试在用户错误使用的特定控件下弹出一个自动关闭的警报窗口。

我目前正在使用DevExpress AlertControl 机制。它的位置需要使用BeforeFormShow 事件来设置,所以我使用以下管理器类来设置它的位置并显示带有特定消息的警报:

class AlertPopper
{
    private AlertControl _alert;
    private Form _form;
    private int _x, _y;

    /// Pass in an AlertControl to be managed by the AlertPopper.
    public AlertPopper(Form form, AlertControl alert)
    {
        _form = form;
        _alert = alert;
        _x = _y = 0;

        _alert.BeforeFormShow += SetAlertLocation;
    }

    private void SetAlertLocation(object sender, AlertFormEventArgs e)
    {
        e.Location = new System.Drawing.Point(_x, _y);
    }

    public void DisplayAlert(int x, int y, string message)
    {
        _x = x;
        _y = y;

        var alertInfo = new AlertInfo("Warning", message);
        _alert.Show(_form, alertInfo);
    }

    public void DisplayAlert(Control control, string message)
    {
        DisplayAlert(control.Location.X, control.Location.Y, message);
    }
}

目的是捕获异常并在相关控件下显示警报,如下所示:

// In form constructor, start the alert manager:
public MyForm()
{
    _alertPopper = new AlertPopper(this, this.AlertWarning);
}


// ... then in some event handler method, display the alert:
private void SomeControl_Click(Control sender, EventArgs e)
{
    // ... in some catch block for a recoverable exception
    _alertPopper.DisplayAlert(sender, "Bad thing happened.");
}

但不是出现在控件下方的警报窗口,而是出现在很远的地方(通常在我设置的两个显示器的错误显示上,但不是在这里):

似乎坐标是相对于我的屏幕角而不是我的窗口角进行处理的。如何获得相对于后者显示的警报?

【问题讨论】:

    标签: c# winforms devexpress


    【解决方案1】:

    你需要使用Control.PointToScreen方法。
    这是您的 DisplayAlert 方法的示例:

    public void DisplayAlert(Control control, string message)
    {
        var point = new Point(control.Width / 2, control.Height);
        var screenPoint = control.PointToScreen(point);
    
        DisplayAlert(screenPoint.X, screenPoint.Y, message);
    }
    

    这是您的事件处理方法:

    private void SomeControl_Click(Control sender, EventArgs e)
    {    
        _alertPopper.DisplayAlert(sender, "Bad thing happened.");
    }
    

    【讨论】:

    • 效果很好。感谢您提供干净的解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多