Office code cleanup, this could improve the COM-object usage a bit.

This commit is contained in:
RKrom 2014-03-17 14:54:27 +01:00
parent 3204b92d53
commit d27df3027b
5 changed files with 252 additions and 188 deletions

View file

@ -133,7 +133,7 @@ namespace GreenshotOfficePlugin {
} }
public override IEnumerable<IDestination> DynamicDestinations() { public override IEnumerable<IDestination> DynamicDestinations() {
Dictionary<string, OlObjectClass> inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets(conf.OutlookAllowExportInMeetings); Dictionary<string, OlObjectClass> inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets();
if (inspectorCaptions != null) { if (inspectorCaptions != null) {
foreach (string inspectorCaption in inspectorCaptions.Keys) { foreach (string inspectorCaption in inspectorCaptions.Keys) {
yield return new OutlookDestination(inspectorCaption, inspectorCaptions[inspectorCaption]); yield return new OutlookDestination(inspectorCaption, inspectorCaptions[inspectorCaption]);
@ -175,7 +175,7 @@ namespace GreenshotOfficePlugin {
exportInformation.ExportMade = true; exportInformation.ExportMade = true;
} else { } else {
if (!manuallyInitiated) { if (!manuallyInitiated) {
Dictionary<string, OlObjectClass> inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets(conf.OutlookAllowExportInMeetings); Dictionary<string, OlObjectClass> inspectorCaptions = OutlookEmailExporter.RetrievePossibleTargets();
if (inspectorCaptions != null && inspectorCaptions.Count > 0) { if (inspectorCaptions != null && inspectorCaptions.Count > 0) {
List<IDestination> destinations = new List<IDestination>(); List<IDestination> destinations = new List<IDestination>();
destinations.Add(new OutlookDestination()); destinations.Add(new OutlookDestination());

View file

@ -31,6 +31,8 @@ using System.Threading;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
using GreenshotPlugin.Core; using GreenshotPlugin.Core;
using GreenshotOfficePlugin;
using Greenshot.IniFile;
namespace Greenshot.Interop.Office { namespace Greenshot.Interop.Office {
/// <summary> /// <summary>
@ -38,6 +40,7 @@ namespace Greenshot.Interop.Office {
/// </summary> /// </summary>
public class OutlookEmailExporter { public class OutlookEmailExporter {
private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookEmailExporter)); private static readonly log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(OutlookEmailExporter));
private static readonly OfficeConfiguration conf = IniConfig.GetIniSection<OfficeConfiguration>();
private static readonly string SIGNATURE_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures"); private static readonly string SIGNATURE_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"Microsoft\Signatures");
private static Version outlookVersion = null; private static Version outlookVersion = null;
private static string currentUser = null; private static string currentUser = null;
@ -56,9 +59,8 @@ namespace Greenshot.Interop.Office {
/// <summary> /// <summary>
/// A method to retrieve all inspectors which can act as an export target /// A method to retrieve all inspectors which can act as an export target
/// </summary> /// </summary>
/// <param name="allowMeetingAsTarget">bool true if also exporting to meetings</param>
/// <returns>List<string> with inspector captions (window title)</returns> /// <returns>List<string> with inspector captions (window title)</returns>
public static Dictionary<string, OlObjectClass> RetrievePossibleTargets(bool allowMeetingAsTarget) { public static Dictionary<string, OlObjectClass> RetrievePossibleTargets() {
Dictionary<string, OlObjectClass> inspectorCaptions = new Dictionary<string, OlObjectClass>(); Dictionary<string, OlObjectClass> inspectorCaptions = new Dictionary<string, OlObjectClass>();
try { try {
using (IOutlookApplication outlookApplication = GetOutlookApplication()) { using (IOutlookApplication outlookApplication = GetOutlookApplication()) {
@ -71,7 +73,7 @@ namespace Greenshot.Interop.Office {
using (var activeExplorer = outlookApplication.ActiveExplorer()) { using (var activeExplorer = outlookApplication.ActiveExplorer()) {
if (activeExplorer != null) { if (activeExplorer != null) {
using (var inlineResponse = activeExplorer.ActiveInlineResponse) { using (var inlineResponse = activeExplorer.ActiveInlineResponse) {
if (canExportToInspector(inlineResponse, allowMeetingAsTarget)) { if (canExportToInspector(inlineResponse)) {
OlObjectClass currentItemClass = inlineResponse.Class; OlObjectClass currentItemClass = inlineResponse.Class;
inspectorCaptions.Add(activeExplorer.Caption, currentItemClass); inspectorCaptions.Add(activeExplorer.Caption, currentItemClass);
} }
@ -86,7 +88,7 @@ namespace Greenshot.Interop.Office {
using (IInspector inspector = outlookApplication.Inspectors[i]) { using (IInspector inspector = outlookApplication.Inspectors[i]) {
string inspectorCaption = inspector.Caption; string inspectorCaption = inspector.Caption;
using (IItem currentItem = inspector.CurrentItem) { using (IItem currentItem = inspector.CurrentItem) {
if (canExportToInspector(currentItem, allowMeetingAsTarget)) { if (canExportToInspector(currentItem)) {
OlObjectClass currentItemClass = currentItem.Class; OlObjectClass currentItemClass = currentItem.Class;
inspectorCaptions.Add(inspector.Caption, currentItemClass); inspectorCaptions.Add(inspector.Caption, currentItemClass);
} }
@ -106,9 +108,8 @@ namespace Greenshot.Interop.Office {
/// Return true if we can export to the supplied inspector /// Return true if we can export to the supplied inspector
/// </summary> /// </summary>
/// <param name="currentItem">the Item to check</param> /// <param name="currentItem">the Item to check</param>
/// <param name="allowMeetingAsTarget">bool true if also exporting to meetings</param>
/// <returns></returns> /// <returns></returns>
private static bool canExportToInspector(IItem currentItem, bool allowMeetingAsTarget) { private static bool canExportToInspector(IItem currentItem) {
try { try {
if (currentItem != null) { if (currentItem != null) {
OlObjectClass currentItemClass = currentItem.Class; OlObjectClass currentItemClass = currentItem.Class;
@ -119,7 +120,7 @@ namespace Greenshot.Interop.Office {
if (!mailItem.Sent) { if (!mailItem.Sent) {
return true; return true;
} }
} else if (outlookVersion.Major >= OUTLOOK_2010 && allowMeetingAsTarget && OlObjectClass.olAppointment.Equals(currentItemClass)) { } else if (outlookVersion.Major >= OUTLOOK_2010 && conf.OutlookAllowExportInMeetings && OlObjectClass.olAppointment.Equals(currentItemClass)) {
//AppointmentItem appointmentItem = COMWrapper.Cast<AppointmentItem>(currentItem); //AppointmentItem appointmentItem = COMWrapper.Cast<AppointmentItem>(currentItem);
AppointmentItem appointmentItem = (AppointmentItem)currentItem; AppointmentItem appointmentItem = (AppointmentItem)currentItem;
if (string.IsNullOrEmpty(appointmentItem.Organizer) || (currentUser != null && currentUser.Equals(appointmentItem.Organizer))) { if (string.IsNullOrEmpty(appointmentItem.Organizer) || (currentUser != null && currentUser.Equals(appointmentItem.Organizer))) {
@ -144,47 +145,48 @@ namespace Greenshot.Interop.Office {
/// <param name="attachmentName">name of the attachment (used as the tooltip of the image)</param> /// <param name="attachmentName">name of the attachment (used as the tooltip of the image)</param>
/// <returns>true if it worked</returns> /// <returns>true if it worked</returns>
public static bool ExportToInspector(string inspectorCaption, string tmpFile, string attachmentName) { public static bool ExportToInspector(string inspectorCaption, string tmpFile, string attachmentName) {
// Assume true, although this might cause issues.
bool allowMeetingAsTarget = true;
using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) { using (IOutlookApplication outlookApplication = GetOrCreateOutlookApplication()) {
if (outlookApplication != null) { if (outlookApplication == null) {
return false;
if (outlookVersion.Major >= OUTLOOK_2013) { }
// Check inline "panel" for Outlook 2013 if (outlookVersion.Major >= OUTLOOK_2013) {
using (var activeExplorer = outlookApplication.ActiveExplorer()) { // Check inline "panel" for Outlook 2013
if (activeExplorer != null) { using (var activeExplorer = outlookApplication.ActiveExplorer()) {
var currentCaption = activeExplorer.Caption; if (activeExplorer == null) {
if (currentCaption.StartsWith(inspectorCaption)) { return false;
using (var inlineResponse = activeExplorer.ActiveInlineResponse) { }
using (IItem currentItem = activeExplorer.ActiveInlineResponse) { var currentCaption = activeExplorer.Caption;
if (canExportToInspector(inlineResponse, allowMeetingAsTarget)) { if (currentCaption.StartsWith(inspectorCaption)) {
try { using (var inlineResponse = activeExplorer.ActiveInlineResponse) {
return ExportToInspector(activeExplorer, currentItem, tmpFile, attachmentName); using (IItem currentItem = activeExplorer.ActiveInlineResponse) {
} catch (Exception exExport) { if (canExportToInspector(inlineResponse)) {
LOG.Error("Export to " + currentCaption + " failed.", exExport); try {
} return ExportToInspector(activeExplorer, currentItem, tmpFile, attachmentName);
} } catch (Exception exExport) {
LOG.Error("Export to " + currentCaption + " failed.", exExport);
} }
} }
} }
} }
} }
} }
}
IInspectors inspectors = outlookApplication.Inspectors; using (IInspectors inspectors = outlookApplication.Inspectors) {
if (inspectors != null && inspectors.Count > 0) { if (inspectors == null || inspectors.Count == 0) {
LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count); return false;
for (int i = 1; i <= inspectors.Count; i++) { }
using (IInspector inspector = outlookApplication.Inspectors[i]) { LOG.DebugFormat("Got {0} inspectors to check", inspectors.Count);
string currentCaption = inspector.Caption; for (int i = 1; i <= inspectors.Count; i++) {
if (currentCaption.StartsWith(inspectorCaption)) { using (IInspector inspector = outlookApplication.Inspectors[i]) {
using (IItem currentItem = inspector.CurrentItem) { string currentCaption = inspector.Caption;
if (canExportToInspector(currentItem, allowMeetingAsTarget)) { if (currentCaption.StartsWith(inspectorCaption)) {
try { using (IItem currentItem = inspector.CurrentItem) {
return ExportToInspector(inspector, currentItem, tmpFile, attachmentName); if (canExportToInspector(currentItem)) {
} catch (Exception exExport) { try {
LOG.Error("Export to " + currentCaption + " failed.", exExport); return ExportToInspector(inspector, currentItem, tmpFile, attachmentName);
} } catch (Exception exExport) {
LOG.Error("Export to " + currentCaption + " failed.", exExport);
} }
} }
} }
@ -252,12 +254,7 @@ namespace Greenshot.Interop.Office {
try { try {
if (WordExporter.InsertIntoExistingDocument(wordDocument.Application, wordDocument, tmpFile, null, null)) { if (WordExporter.InsertIntoExistingDocument(wordDocument.Application, wordDocument, tmpFile, null, null)) {
LOG.Info("Inserted into Wordmail"); LOG.Info("Inserted into Wordmail");
wordDocument.Dispose();
// check the format afterwards, otherwise we lose the selection
//if (!OlBodyFormat.olFormatHTML.Equals(currentMail.BodyFormat)) {
// LOG.Info("Changing format to HTML.");
// currentMail.BodyFormat = OlBodyFormat.olFormatHTML;
//}
return true; return true;
} }
} catch (Exception exportException) { } catch (Exception exportException) {
@ -324,6 +321,7 @@ namespace Greenshot.Interop.Office {
IPropertyAccessor propertyAccessor = attachment.PropertyAccessor; IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID); propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
} catch { } catch {
// Ignore
} }
} }
} }
@ -347,90 +345,98 @@ namespace Greenshot.Interop.Office {
/// <param name="tmpFile"></param> /// <param name="tmpFile"></param>
/// <param name="captureDetails"></param> /// <param name="captureDetails"></param>
private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url) { private static void ExportToNewEmail(IOutlookApplication outlookApplication, EmailFormat format, string tmpFile, string subject, string attachmentName, string to, string CC, string BCC, string url) {
IItem newItem = outlookApplication.CreateItem(OlItemType.olMailItem); using (IItem newItem = outlookApplication.CreateItem(OlItemType.olMailItem)) {
if (newItem == null) { if (newItem == null) {
return; return;
} }
//MailItem newMail = COMWrapper.Cast<MailItem>(newItem); //MailItem newMail = COMWrapper.Cast<MailItem>(newItem);
MailItem newMail = (MailItem)newItem; MailItem newMail = (MailItem)newItem;
newMail.Subject = subject; newMail.Subject = subject;
if (!string.IsNullOrEmpty(to)) { if (!string.IsNullOrEmpty(to)) {
newMail.To = to; newMail.To = to;
} }
if (!string.IsNullOrEmpty(CC)) { if (!string.IsNullOrEmpty(CC)) {
newMail.CC = CC; newMail.CC = CC;
} }
if (!string.IsNullOrEmpty(BCC)) { if (!string.IsNullOrEmpty(BCC)) {
newMail.BCC = BCC; newMail.BCC = BCC;
} }
newMail.BodyFormat = OlBodyFormat.olFormatHTML; newMail.BodyFormat = OlBodyFormat.olFormatHTML;
string bodyString = null; string bodyString = null;
// Read the default signature, if nothing found use empty email // Read the default signature, if nothing found use empty email
try { try {
bodyString = GetOutlookSignature(format); bodyString = GetOutlookSignature(format);
} catch (Exception e) { } catch (Exception e) {
LOG.Error("Problem reading signature!", e); LOG.Error("Problem reading signature!", e);
} }
switch (format) { switch (format) {
case EmailFormat.Text: case EmailFormat.Text:
newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName); // Create the attachment (and dispose the COM object after using)
newMail.BodyFormat = OlBodyFormat.olFormatPlain; using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 1, attachmentName)) {
if (bodyString == null) { newMail.BodyFormat = OlBodyFormat.olFormatPlain;
bodyString = ""; if (bodyString == null) {
} bodyString = "";
newMail.Body = bodyString; }
break; newMail.Body = bodyString;
case EmailFormat.HTML: }
default: break;
string contentID = Path.GetFileName(tmpFile); case EmailFormat.HTML:
// Create the attachment default:
using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) { string contentID = Path.GetFileName(tmpFile);
// add content ID to the attachment // Create the attachment (and dispose the COM object after using)
if (outlookVersion.Major >= OUTLOOK_2007) { using (IAttachment attachment = newMail.Attachments.Add(tmpFile, OlAttachmentType.olByValue, 0, attachmentName)) {
try { // add content ID to the attachment
contentID = Guid.NewGuid().ToString(); if (outlookVersion.Major >= OUTLOOK_2007) {
IPropertyAccessor propertyAccessor = attachment.PropertyAccessor; try {
propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID); contentID = Guid.NewGuid().ToString();
} catch { IPropertyAccessor propertyAccessor = attachment.PropertyAccessor;
LOG.Info("Error working with the PropertyAccessor, using filename as contentid"); propertyAccessor.SetProperty(PropTag.ATTACHMENT_CONTENT_ID, contentID);
contentID = Path.GetFileName(tmpFile); } catch {
LOG.Info("Error working with the PropertyAccessor, using filename as contentid");
contentID = Path.GetFileName(tmpFile);
}
} }
} }
}
newMail.BodyFormat = OlBodyFormat.olFormatHTML; newMail.BodyFormat = OlBodyFormat.olFormatHTML;
string href = ""; string href = "";
string hrefEnd = ""; string hrefEnd = "";
if (!string.IsNullOrEmpty(url)) { if (!string.IsNullOrEmpty(url)) {
href = string.Format("<A HREF=\"{0}\">", url); href = string.Format("<A HREF=\"{0}\">", url);
hrefEnd = "</A>"; hrefEnd = "</A>";
} }
string htmlImgEmbedded = string.Format("<BR/>{0}<IMG border=0 hspace=0 alt=\"{1}\" align=baseline src=\"cid:{2}\">{3}<BR/>", href, attachmentName, contentID, hrefEnd); string htmlImgEmbedded = string.Format("<BR/>{0}<IMG border=0 hspace=0 alt=\"{1}\" align=baseline src=\"cid:{2}\">{3}<BR/>", href, attachmentName, contentID, hrefEnd);
string fallbackBody = string.Format("<HTML><BODY>{0}</BODY></HTML>", htmlImgEmbedded); string fallbackBody = string.Format("<HTML><BODY>{0}</BODY></HTML>", htmlImgEmbedded);
if (bodyString == null) { if (bodyString == null) {
bodyString = fallbackBody; bodyString = fallbackBody;
} else { } else {
int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase); int bodyIndex = bodyString.IndexOf("<body", StringComparison.CurrentCultureIgnoreCase);
if (bodyIndex >= 0) {
bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
if (bodyIndex >= 0) { if (bodyIndex >= 0) {
bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded); bodyIndex = bodyString.IndexOf(">", bodyIndex) + 1;
if (bodyIndex >= 0) {
bodyString = bodyString.Insert(bodyIndex, htmlImgEmbedded);
} else {
bodyString = fallbackBody;
}
} else { } else {
bodyString = fallbackBody; bodyString = fallbackBody;
} }
} else { }
bodyString = fallbackBody; newMail.HTMLBody = bodyString;
break;
}
// So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
newMail.Display(false);
using (IInspector inspector = newMail.GetInspector()) {
if (inspector != null) {
try {
inspector.Activate();
} catch {
// Ignore
} }
} }
newMail.HTMLBody = bodyString; }
break;
}
// So not save, otherwise the email is always stored in Draft folder.. (newMail.Save();)
newMail.Display(false);
newMail.GetInspector().Activate();
if (newItem != null) {
newItem.Dispose();
} }
} }

View file

@ -40,24 +40,32 @@ namespace Greenshot.Interop.Office {
/// Get the captions of all the open powerpoint presentations /// Get the captions of all the open powerpoint presentations
/// </summary> /// </summary>
/// <returns></returns> /// <returns></returns>
public static System.Collections.Generic.List<string> GetPowerpointPresentations() { public static List<string> GetPowerpointPresentations() {
System.Collections.Generic.List<string> presentations = new System.Collections.Generic.List<string>(); List<string> foundPresentations = new System.Collections.Generic.List<string>();
try { try {
using (IPowerpointApplication powerpointApplication = COMWrapper.GetInstance<IPowerpointApplication>()) { using (IPowerpointApplication powerpointApplication = COMWrapper.GetInstance<IPowerpointApplication>()) {
if (powerpointApplication != null) { if (powerpointApplication == null) {
if (version == null) { return foundPresentations;
version = powerpointApplication.Version; }
} if (version == null) {
LOG.DebugFormat("Open Presentations: {0}", powerpointApplication.Presentations.Count); version = powerpointApplication.Version;
for (int i = 1; i <= powerpointApplication.Presentations.Count; i++) { }
IPresentation presentation = powerpointApplication.Presentations.item(i); using (IPresentations presentations = powerpointApplication.Presentations) {
if (presentation != null && presentation.ReadOnly != MsoTriState.msoTrue) { LOG.DebugFormat("Open Presentations: {0}", presentations.Count);
for (int i = 1; i <= presentations.Count; i++) {
using (IPresentation presentation = presentations.item(i)) {
if (presentation == null) {
continue;
}
if (presentation.ReadOnly == MsoTriState.msoTrue) {
continue;
}
if (isAfter2003()) { if (isAfter2003()) {
if (presentation.Final) { if (presentation.Final) {
continue; continue;
} }
} }
presentations.Add(presentation.Name); foundPresentations.Add(presentation.Name);
} }
} }
} }
@ -66,7 +74,7 @@ namespace Greenshot.Interop.Office {
LOG.Warn("Problem retrieving word destinations, ignoring: ", ex); LOG.Warn("Problem retrieving word destinations, ignoring: ", ex);
} }
return presentations; return foundPresentations;
} }
/// <summary> /// <summary>
@ -79,11 +87,19 @@ namespace Greenshot.Interop.Office {
/// <returns></returns> /// <returns></returns>
public static bool ExportToPresentation(string presentationName, string tmpFile, Size imageSize, string title) { public static bool ExportToPresentation(string presentationName, string tmpFile, Size imageSize, string title) {
using (IPowerpointApplication powerpointApplication = COMWrapper.GetInstance<IPowerpointApplication>()) { using (IPowerpointApplication powerpointApplication = COMWrapper.GetInstance<IPowerpointApplication>()) {
if (powerpointApplication != null) { if (powerpointApplication == null) {
LOG.DebugFormat("Open Presentations: {0}", powerpointApplication.Presentations.Count); return false;
for (int i = 1; i <= powerpointApplication.Presentations.Count; i++) { }
IPresentation presentation = powerpointApplication.Presentations.item(i); using (IPresentations presentations = powerpointApplication.Presentations) {
if (presentation != null && presentation.Name.StartsWith(presentationName)) { LOG.DebugFormat("Open Presentations: {0}", presentations.Count);
for (int i = 1; i <= presentations.Count; i++) {
using (IPresentation presentation = presentations.item(i)) {
if (presentation == null) {
continue;
}
if (!presentation.Name.StartsWith(presentationName)) {
continue;
}
try { try {
AddPictureToPresentation(presentation, tmpFile, imageSize, title); AddPictureToPresentation(presentation, tmpFile, imageSize, title);
return true; return true;
@ -97,47 +113,62 @@ namespace Greenshot.Interop.Office {
return false; return false;
} }
/// <summary>
/// Internal method to add a picture to a presentation
/// </summary>
/// <param name="presentation"></param>
/// <param name="tmpFile"></param>
/// <param name="imageSize"></param>
/// <param name="title"></param>
private static void AddPictureToPresentation(IPresentation presentation, string tmpFile, Size imageSize, string title) { private static void AddPictureToPresentation(IPresentation presentation, string tmpFile, Size imageSize, string title) {
if (presentation != null) { if (presentation == null) {
//ISlide slide = presentation.Slides.AddSlide( presentation.Slides.Count + 1, PPSlideLayout.ppLayoutPictureWithCaption); return;
ISlide slide; }
float left = (presentation.PageSetup.SlideWidth / 2) - (imageSize.Width / 2) ; ISlide slide;
float top = (presentation.PageSetup.SlideHeight / 2) - (imageSize.Height / 2); float left = (presentation.PageSetup.SlideWidth / 2) - (imageSize.Width / 2) ;
float width = imageSize.Width; float top = (presentation.PageSetup.SlideHeight / 2) - (imageSize.Height / 2);
float height = imageSize.Height; float width = imageSize.Width;
bool isLayoutPictureWithCaption = false; float height = imageSize.Height;
IShape shapeForCaption = null; bool isLayoutPictureWithCaption = false;
bool hasScaledWidth = false; IShape shapeForCaption = null;
bool hasScaledHeight = false; bool hasScaledWidth = false;
bool hasScaledHeight = false;
// Try to create the slide
using (ISlides slides = presentation.Slides) {
try { try {
slide = presentation.Slides.Add(presentation.Slides.Count + 1, (int)PPSlideLayout.ppLayoutPictureWithCaption); slide = slides.Add(slides.Count + 1, (int)PPSlideLayout.ppLayoutPictureWithCaption);
isLayoutPictureWithCaption = true; isLayoutPictureWithCaption = true;
// Shapes[2] is the image shape on this layout. // Shapes[2] is the image shape on this layout.
shapeForCaption = slide.Shapes.item(1); shapeForCaption = slide.Shapes.item(1);
IShape shapeForLocation = slide.Shapes.item(2); using (IShape shapeForLocation = slide.Shapes.item(2)) {
if (width > shapeForLocation.Width) {
width = shapeForLocation.Width;
left = shapeForLocation.Left;
hasScaledWidth = true;
} else {
shapeForLocation.Left = left;
}
shapeForLocation.Width = imageSize.Width;
if (width > shapeForLocation.Width) { if (height > shapeForLocation.Height) {
width = shapeForLocation.Width; height = shapeForLocation.Height;
left = shapeForLocation.Left; top = shapeForLocation.Top;
hasScaledWidth = true; hasScaledHeight = true;
} else { } else {
shapeForLocation.Left = left; top = (shapeForLocation.Top + (shapeForLocation.Height / 2)) - (imageSize.Height / 2);
}
shapeForLocation.Height = imageSize.Height;
} }
shapeForLocation.Width = imageSize.Width;
if (height > shapeForLocation.Height) {
height = shapeForLocation.Height;
top = shapeForLocation.Top;
hasScaledHeight = true;
} else {
top = (shapeForLocation.Top + (shapeForLocation.Height / 2)) - (imageSize.Height / 2);
}
shapeForLocation.Height = imageSize.Height;
} catch (Exception e) { } catch (Exception e) {
LOG.Error(e); LOG.Error(e);
slide = presentation.Slides.Add(presentation.Slides.Count + 1, (int)PPSlideLayout.ppLayoutBlank); // didn't work. Use simple slide layout
slide = slides.Add(slides.Count + 1, (int)PPSlideLayout.ppLayoutBlank);
} }
IShape shape = slide.Shapes.AddPicture(tmpFile, MsoTriState.msoFalse, MsoTriState.msoTrue, 0, 0, width, height); }
// Make sure the picture is added and correctly scaled
using (IShape shape = slide.Shapes.AddPicture(tmpFile, MsoTriState.msoFalse, MsoTriState.msoTrue, 0, 0, width, height)) {
shape.LockAspectRatio = MsoTriState.msoTrue; shape.LockAspectRatio = MsoTriState.msoTrue;
shape.ScaleHeight(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle); shape.ScaleHeight(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle);
shape.ScaleWidth(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle); shape.ScaleWidth(1, MsoTriState.msoTrue, MsoScaleFrom.msoScaleFromMiddle);
@ -145,37 +176,64 @@ namespace Greenshot.Interop.Office {
shape.Width = width; shape.Width = width;
} }
if (hasScaledHeight) { if (hasScaledHeight) {
shape.Height = height; shape.Height = height;
} }
shape.Left = left; shape.Left = left;
shape.Top = top; shape.Top = top;
shape.AlternativeText = title; shape.AlternativeText = title;
if (isLayoutPictureWithCaption && shapeForCaption != null) { }
// Try settings the caption
if (shapeForCaption != null) {
if (isLayoutPictureWithCaption) {
try { try {
// Using try/catch to make sure problems with the text range don't give an exception. // Using try/catch to make sure problems with the text range don't give an exception.
ITextFrame textFrame = shapeForCaption.TextFrame; using (ITextFrame textFrame = shapeForCaption.TextFrame) {
textFrame.TextRange.Text = title; textFrame.TextRange.Text = title;
}
} catch (Exception ex) { } catch (Exception ex) {
LOG.Warn("Problem setting the title to a text-range", ex); LOG.Warn("Problem setting the title to a text-range", ex);
} }
} }
presentation.Application.ActiveWindow.View.GotoSlide(slide.SlideNumber); shapeForCaption.Dispose();
presentation.Application.Activate(); }
// Show the window, and show the new slide
using (IPowerpointApplication application = presentation.Application) {
using (IPowerpointWindow activeWindow = application.ActiveWindow) {
using (IPowerpointView view = activeWindow.View) {
view.GotoSlide(slide.SlideNumber);
}
}
application.Activate();
}
if (slide != null) {
slide.Dispose();
} }
} }
/// <summary>
/// Insert a capture into a new presentation
/// </summary>
/// <param name="tmpFile"></param>
/// <param name="imageSize"></param>
/// <param name="title"></param>
/// <returns></returns>
public static bool InsertIntoNewPresentation(string tmpFile, Size imageSize, string title) { public static bool InsertIntoNewPresentation(string tmpFile, Size imageSize, string title) {
bool isPictureAdded = false; bool isPictureAdded = false;
using (IPowerpointApplication powerpointApplication = COMWrapper.GetOrCreateInstance<IPowerpointApplication>()) { using (IPowerpointApplication powerpointApplication = COMWrapper.GetOrCreateInstance<IPowerpointApplication>()) {
if (powerpointApplication != null) { if (powerpointApplication == null) {
powerpointApplication.Visible = true; return isPictureAdded;
IPresentation presentation = powerpointApplication.Presentations.Add(MsoTriState.msoTrue); }
try { powerpointApplication.Visible = true;
AddPictureToPresentation(presentation, tmpFile, imageSize, title); using (IPresentations presentations = powerpointApplication.Presentations) {
isPictureAdded = true; using (IPresentation presentation = presentations.Add(MsoTriState.msoTrue)) {
presentation.Application.Activate(); try {
} catch (Exception e) { AddPictureToPresentation(presentation, tmpFile, imageSize, title);
LOG.Error(e); isPictureAdded = true;
} catch (Exception e) {
LOG.Error(e);
}
} }
} }
} }

View file

@ -555,7 +555,7 @@ namespace GreenshotPlugin.Core {
tmpFileCache.Remove(tmpfile); tmpFileCache.Remove(tmpfile);
} }
return true; return true;
} catch (Exception e) { } catch (Exception) {
} }
return false; return false;
} }

View file

@ -6,6 +6,6 @@ namespace Greenshot.Interop {
/// <summary> /// <summary>
/// Common properties that has appreared in almost all objects /// Common properties that has appreared in almost all objects
/// </summary> /// </summary>
public interface Common : IDisposable { public interface ICommon : IDisposable {
} }
} }