c# - 尝试打开 Outlook 电子邮件时出现 WPF 任务/线程问题
问题描述
我有一个 WPF 应用程序,其中有一部分用户基本上填写类似 Outlook 的表单,然后用适当的信息填充 Outlook 电子邮件。问题是,当这封电子邮件打开时,代码执行会停止,直到电子邮件被发送或关闭。
我试图将它放在一个新线程上,但我在各个地方遇到了各种各样的问题,以使其工作。电子邮件表单的“正文”是一个富文本框,需要在将其放入 Outlook 电子邮件之前对其进行格式化,以使其正确显示。
从我读到的剪贴板调用必须放在他们自己的 STA 线程上,但在完成之前它会返回 null。
我怎样才能让它正常工作?基本上我想要的只是让 Outlook 电子邮件项位于其自己的线程上,这样它就不会在主线程打开时阻止其执行。
private async Task CreateEmail()
{
try
{
//create an outlook object
await Task.Run(() =>
{
MyOutlook.Application oApp = new MyOutlook.Application();
//we need to check the to strings of that various items and join them together
var toStrings = emailForm.ToMain;
toStrings += String.IsNullOrEmpty(emailForm.ToRM) ? "" : ";" + emailForm.ToRM;
toStrings += String.IsNullOrEmpty(emailForm.ToSM) ? "" : ";" + emailForm.ToSM;
MyOutlook.MailItem oMailItem = (MyOutlook.MailItem)oApp.CreateItem(MyOutlook.OlItemType.olMailItem);
oMailItem.To = toStrings;
oMailItem.CC = emailForm.CC;
oMailItem.BCC = emailForm.BCC;
oMailItem.Subject = emailForm.Subject;
oMailItem.RTFBody = GetRTBText();
oMailItem.Display(true);
});
}
catch(Exception ex)
{
ErrorWindow errWin = new ErrorWindow("There was an error creating the Outlook Email! Error: " + ex.Message);
errWin.Show();
}
}
private byte[] GetRTBText()
{
byte[] RTFArr = null;
//need to create a new STA Thread for the clipboard
Thread thread = new Thread(() => Clipboard.Clear());
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
this.Dispatcher.Invoke(() =>
{
RTBBody.SelectAll();
RTBBody.Copy();
});
Thread thread2 = new Thread(() => RTFArr = Encoding.UTF8.GetBytes (Clipboard.GetText(TextDataFormat.Rtf)));
thread2.SetApartmentState(ApartmentState.STA);
thread2.Start();
thread.Join();
return RTFArr;
}
解决方案
不要调用 Display(true) - 这将以模态方式显示消息。调用显示(假)。
推荐阅读
- xml - 如何根据xml中的字段名称值获取节点?
- javascript - 正则表达式不采用 JavaScript 中的最后一个结果
- qt - QML 地图仅垂直缩放
- c# - 有没有办法预先构建在 Simple Injector 容器中注册的所有服务?
- react-admin - ReferenceInput :使用 GET_ONE 而不是 GET_MANY 就像在 admin-on-rest 中所做的那样
- kubernetes - connection refused to localhost:8080
- azure - 为什么使用 Get-AzureRMStorageAccount 时连接字符串为空?
- c# - 创建新计时器时,旧计时器会发生什么?
- excel - Excel:CountIFS - 多个条件且不为空
- r - 将数据重组为面板格式 - 跨列提取单元格值