You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从WinForms应用打开MS Teams向指定用户发送聊天消息?

回答

这个需求可以实现,实现逻辑和你现有唤起邮件客户端的方案同源:Microsoft Teams 支持原生URL协议,无需接入额外SDK,直接调用系统进程启动协议地址,即可拉起Teams客户端并定位到指定联系人的聊天窗口。

你当前的邮件超链接实现代码:

private void ContactDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 2) // Assuming it's the first column
    {
        Process.Start("mailto:" + 
            ContactDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
    }
}

核心实现规则

  • Teams 拉起单聊的协议格式为 msteams:/l/chat/0/0?users=<联系人登录Teams所用的邮箱地址>
  • 单元格中存储的联系人信息需要是对方登录Teams的有效邮箱,拼接后即可直接调用,逻辑和mailto协议完全一致
  • 若目标联系人为当前Teams租户内用户,会直接打开已有单聊窗口;若为外部用户,会自动弹出新建聊天的确认页
  • 若设备未安装Teams桌面端,系统会自动跳转至网页版Teams加载对应聊天,无需额外兼容

改造后代码

你只需要新增对应Teams列的点击判断,替换协议头即可,示例如下(假设Teams联系人列索引为3,可根据实际列位置调整):

private void ContactDataGrid_CellClick(object sender, DataGridViewCellEventArgs e)
{
    // 过滤表头点击的无效场景
    if (e.RowIndex < 0) return;

    // 原有邮件列逻辑
    if (e.ColumnIndex == 2)
    {
        string email = ContactDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
        if (!string.IsNullOrWhiteSpace(email))
        {
            Process.Start(new ProcessStartInfo($"mailto:{email}") { UseShellExecute = true });
        }
    }

    // 新增Teams聊天列逻辑
    if (e.ColumnIndex == 3)
    {
        string contactEmail = ContactDataGrid.Rows[e.RowIndex].Cells[e.ColumnIndex].Value?.ToString();
        if (!string.IsNullOrWhiteSpace(contactEmail))
        {
            string teamsProtocolUrl = $"msteams:/l/chat/0/0?users={contactEmail}";
            Process.Start(new ProcessStartInfo(teamsProtocolUrl) { UseShellExecute = true });
        }
    }
}

注意事项:在 .NET Core / .NET 5+ 环境下调用自定义协议,必须显式设置UseShellExecute = true,否则会抛出文件找不到的异常,该行为和.NET Framework环境有差异。

内容的提问来源于stack exchange,提问作者jacko10101

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 23:27:32