我需要帮助解决我添加 Outlook 任务的代码的问题。它在某些系统上运行正常,但在安装了 Office 365 的计算机上运行不正常。具体来说,当 Outlook 已在此计算机上打开时,我的代码会产生错误。但是,当 Outlook 关闭时,代码可以正常工作。我可以采取什么步骤来解决这个问题?
procedure CreateOutlookReminder(const Subject, Body, Location: string;
const Start, Duration: TDateTime;
const ReminderMinutesBeforeStart: Integer);
var
Outlook, Calendar, AppointmentItem: OleVariant;
begin
// Connect to Outlook
try
try
Outlook := GetActiveOleObject('Outlook.Application');
except
Outlook := CreateOleObject('Outlook.Application');
end
Except
on E: Exception do
begin
MessageDlg('Unable to add reminder.' + #13#10 +
'The version of outlook on your machine is either unsupported or it does not exist.'
+ E.Message, mtError, [mbOK], 0);
Exit
end;
end;
Calendar := Outlook.GetNamespace('MAPI').GetDefaultFolder(13);
// olFolderCalendar
// Create the Task
AppointmentItem := Calendar.Items.Add; // Task
AppointmentItem.Subject := Subject;
AppointmentItem.Body := Body;
AppointmentItem.remindertime := formatdatetime('mm/dd/yy h:nn:ss ampm',
Duration);
AppointmentItem.duedate := Duration;
// Set the reminder
AppointmentItem.ReminderSet := True;
// Save and display the appointment
AppointmentItem.Save;
Outlook := unAssigned;
end;
确保您的代码未以提升的权限运行 - Outlook 是单例,因此当您调用
CreateOleObject
(没有理由为 Outlook 调用 GetActiveOleObject
)时,它会返回一个指向已运行实例的指针。如果 Outlook 和您的代码在不同的安全上下文中运行(例如,一个以“以管理员身份运行”),COM 系统将拒绝编组调用。
当 Outlook 已经在这台机器上打开时,我的代码会产生错误。
确保您在 Windows 中的相同安全上下文 下运行您的应用程序。这意味着如果其中一个应用程序具有管理员权限(提升),另一个应用程序也应该以管理员权限运行 (
Run As Administrator
)。否则,两个应用程序将找不到对方。
另一个因素是您不能在系统上创建一个新的 Outlook 应用程序实例,如果它已经在运行的话。这意味着如果您有一个实例在不同的安全上下文下运行,您将无法连接到它或创建一个新的
Application
实例。