【问题标题】:Why this MessageBox does not appear?为什么这个 MessageBox 没有出现?
【发布时间】:2014-02-21 09:29:36
【问题描述】:

我有下面这样的 EventHandler 代码。

void ConnectionManager_Error(object sender, EventArgs<string> e)
{
    BeginInvoke((MethodInvoker)delegate()
    {
         State = ConnectState.NotFound;
         MessageBox.Show(e.Value);
    });
}

我的问题:

即使设备未连接到计算机,MessageBox 也不会出现。

我认为 MessageBox 应该显示错误消息。 谁能告诉我有什么问题?

注意:

我有这段代码,我认为它会触发 ConnectionManager 错误事件处理程序。

private void LogError(string error)
{
    if (Error != null)
        Error(this, new EventArgs<string>(error));
}

我也有这段代码,它向 LogError 方法提供包含字符串的错误消息。

int lasterror = Marshal.GetLastWin32Error();
    if (lasterror != 0)
        LogError("Bluetooth API returned: " + lasterror.ToString());

 if (BluetoothSetServiceState(IntPtr.Zero, ref device, ref HumanInterfaceDeviceServiceClass_UUID, BLUETOOTH_SERVICE_ENABLE) != 0)
     LogError("Failed to connect to wiimote controller");

另一个提示

更具体地说,我也已经有了下面的代码:

public event EventHandler<EventArgs<string>> Error;

ConnectionManager.Error += new EventHandler<EventArgs<string>>(ConnectionManager_Error);

还有这个类:

public class EventArgs<T> : EventArgs
{
    public T Value
    {
         get;
         set;
    }

     public EventArgs(T value)
            : base()
     {
        Value = value;
     }
}

【问题讨论】:

  • 您是否尝试调试过您的代码?在事件处理程序的第一行设置断点
  • 我试过了,好像没什么问题。这可能是因为我在与用于创建此代码的 VS 不同的 VStudio 版本中执行此项目吗? 愚蠢的问题。
  • 在单独的线程中执行代码是标准的 BeginInvoke 吗?
  • 这是在非 UI 线程中发生的吗?或者 BeginInvoke 的其他原因是什么?

标签: c# event-handling bluetooth message


【解决方案1】:

在单独的线程中执行代码是标准的 BeginInvoke 吗?

您只能在 GUI 线程中使用 GUI 方法。 要切换到 GUI 线程,请尝试 Control.IsInvokeRequired 和 Control.Invoke 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 2022-10-07
    • 2012-10-07
    • 2015-02-06
    • 2016-01-05
    相关资源
    最近更新 更多