Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [링크 복사], [링크+제목 복사]
조회: 15675
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

C# - PowerPoint 확장 Add-in 만드는 방법

이에 대해 마이크로소프트의 문서가 물론 있습니다. ^^

Walkthrough: Creating a Custom Tab by Using Ribbon XML
; https://docs.microsoft.com/en-us/visualstudio/vsto/walkthrough-creating-a-custom-tab-by-using-ribbon-xml

그런데, 제목이 "Ribbon"이라서 다소 혼란스러울 수 있는데 컨텍스트 메뉴 등도 이를 통해 구현할 수 있으므로 "Ribbon"이라는 말 대신 "Add-in"이라고 넣고 해석하셔도 무방합니다.




실제로 PowerPoint의 Shape에 대한 컨텍스트 메뉴를 하나 넣는 것을 구현해 볼 텐데요. Visual Studio 2017의 경우 C# 프로젝트로 "Office/SharePoint" / "PowerPoint 2013 and 2016 VSTO Add-in"을 선택하는 것으로 시작합니다.

그럼, ThisAddIn.cs 파일이 생성되는데 소스 코드는 다음과 같이 간단합니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;

namespace PowerPointAddIn1
{
    public partial class ThisAddIn
    {
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {
        }

        #region VSTO generated code

        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }
        
        #endregion
    }
}

(직관적으로 알 수 있겠지만) 당연히 BP(BreakPoint)를 ThisAddIn_Startup에 걸어 두고 실행하면 PowerPoint가 실행되면서 BP에서 멈추는 것을 확인할 수 있습니다. 사실, 보이는 소스 코드는 작지만 "partial"로 정의되어 있어 (숨김 파일로 있는) ThisAddIn.Designer.cs에 정의된 ThisAddIn의 코드와 합쳐져 다양한 기능을 제공합니다.

namespace PowerPointAddIn1 
{    
    //...[생략]...
    [Microsoft.VisualStudio.Tools.Applications.Runtime.StartupObjectAttribute(0)]
    [global::System.Security.Permissions.PermissionSetAttribute(global::System.Security.Permissions.SecurityAction.Demand, Name="FullTrust")]
    public sealed partial class ThisAddIn : Microsoft.Office.Tools.AddInBase {
        
        //...[생략]...
    
        protected override void FinishInitialization() {
            this.InternalStartup();
            this.OnStartup();
        }
    }
}

보는 바와 같이, InternalStartup 메서드도 결국 FinishInitialization 가상 메서드 내부에서 호출해 주는 구조입니다.




그럼, Shape에 대한 Context Menu를 정의해 보겠습니다. 이를 위해 "새 항목 추가"로 "Office/SharePoint" / "Ribbon (XML)"을 선택합니다. (새 파일 이름을 "Ribbon.cs"로 했을 때 Ribbon.cs 파일과 Ribbon.xml 파일이 함께 생성됩니다.)

기본 생성되는 Ribbon.xml에서 우리는 Ribbon이 필요 없으므로 내용을 삭제하고 다음과 같이 contextMenu 노드를 추가해 줍니다.

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <contextMenus>
    <contextMenu idMso="ContextMenuShape">
      <button id="idCustomShow" label="Make Custom" onAction="OnCustomShowFromSection" />
    </contextMenu>
</customUI>

그다음, "ThisAddIn" 클래스에 Ribbon 인스턴스를 생성하도록 다음의 코드를 추가합니다.

protected override Microsoft.Office.Core.IRibbonExtensibility CreateRibbonExtensibilityObject()
{
    Ribbon ribbon = new Ribbon();
    ribbon.AddIn = this;

    return ribbon;
}

이어서 Ribbon.cs 파일은 Ribbon.xml에 정의한 onAction에 해당하는 이벤트 핸들러와 함께 ThisAddIn 클래스에 대한 참조를 가지도록 속성을 하나 추가해 줍니다.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Office.Interop.PowerPoint;
using Office = Microsoft.Office.Core;

namespace PowerPointAddIn1
{
    [ComVisible(true)]
    public class Ribbon : Office.IRibbonExtensibility
    {
        private Office.IRibbonUI ribbon;

        public ThisAddIn AddIn { get; internal set; }

        // ...[생략: 자동 생성 코드]...

        public void OnCustomShowFromSection(Microsoft.Office.Core.IRibbonControl control)
        {
            Selection selection = this.AddIn.Application.ActiveWindow.Selection;
            Shape shape = selection.ShapeRange[1]; // 사용자가 우 클릭한 Shape

            if (shape.Type == Office.MsoShapeType.msoLine)
            {
                // ... [Line 타입의 Shape가 선택된 경우 원하는 코드 추가]...
            }
        }

        #region Helpers

        private static string GetResourceText(string resourceName)
        {
            // ...[생략: 자동 생성 코드]...
        }

        #endregion
    }
}

이제, BP를 OnCustomShowFromSection 이벤트 핸들러에 설정하고 실행한 후 PPT에 Shape을 하나 추가한 다음 마우스 우 클릭을 하면 다음과 같이 "Make Custom" 메뉴가 보이고,

custom_menu_on_shape_in_ppt_1.png

해당 메뉴를 선택하면 OnCustomShowFromSection의 BP가 걸리는 것을 확인할 수 있습니다.

이후의 코드는 여러분이 원하는 데로 Shape 객체로 다양한 정보를 구해 조작을 하시면 됩니다.




어떤 상황에서의 우 클릭 메뉴를 선택할지에 대해서는 Ribbon.xml의 "contextMenu[@idMso]"를 통해서 지정할 수 있습니다. 이 글의 예제에서는,

<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
  <contextMenus>
    <contextMenu idMso="ContextMenuShape">
      <button id="idCustomShow" label="Make Custom" onAction="OnCustomShowFromSection" />
    </contextMenu>
</customUI>

idMso 값을 ContextMenuShape로 했기 때문에 "Shape"에 대한 컨텍스트 메뉴에 메뉴를 추가할 수 있었던 것입니다. 물론, 다른 상황에서의 컨텍스트 메뉴도 추가할 수 있는데 이를 위해서는 idMso에 대한 값을 알아야 합니다. 검색해 보면, PowerPoint 2010 기준으로 다음의 문서를 다운로드할 수 있습니다.

idMso Exists in Office PowerPoint 2010 Type in Office PowerPoint 
; http://download.microsoft.com/download/4/2/B/42B7A409-3411-464F-B029-6A9D48E93322/PowerPointControls.txt

문서에 따라, 컨텍스트 메뉴를 위한 idMso 값이 이렇게나 많이 제공됩니다. ^^;

ContextMenuActiveXControl 
ContextMenuAddressBlock 
ContextMenuBroadcast 
ContextMenuCanvas 
ContextMenuCanvasClassic 
ContextMenuChartArea 
ContextMenuChartAxis 
ContextMenuChartAxisTitle 
ContextMenuChartBackWall 
ContextMenuChartDataLabel 
ContextMenuChartDataLabels 
ContextMenuChartDataPoint 
ContextMenuChartDataSeries 
ContextMenuChartDataTable 
ContextMenuChartDisplayUnit 
ContextMenuChartDownBars 
ContextMenuChartDropLines 
ContextMenuChartErrorBars 
ContextMenuChartFloor 
ContextMenuChartGridlines 
ContextMenuChartHighLowLine 
ContextMenuChartLeaderLines 
ContextMenuChartLegend 
ContextMenuChartLegendEntry 
ContextMenuChartParetoLine 
ContextMenuChartPlotArea 
ContextMenuChartSeriesLine 
ContextMenuChartSideWall 
ContextMenuChartTitle 
ContextMenuChartTrendline 
ContextMenuChartTrendlineLabel 
ContextMenuChartUpBars 
ContextMenuChartWalls 
ContextMenuCoAuthoringState 
ContextMenuComment 
ContextMenuConflicts 
ContextMenuConnectorClassic 
ContextMenuCurve 
ContextMenuCurveNode 
ContextMenuCurveSegment 
ContextMenuDiagram 
ContextMenuDocumentStructureNode 
ContextMenuDrawnObject 
ContextMenuDropCap 
ContextMenuEndnote 
ContextMenuEquation 
ContextMenuField 
ContextMenuFieldAutoSignatureList 
ContextMenuFieldAutoTextList 
ContextMenuFieldDisplay 
ContextMenuFieldDisplayListNumbers 
ContextMenuFieldForm 
ContextMenuFloatingPicture 
ContextMenuFooterArea 
ContextMenuFootnote 
ContextMenuFrame 
ContextMenuFramesetBorder 
ContextMenuGrammar 
ContextMenuGrammarReading 
ContextMenuGreetingLine 
ContextMenuHeaderArea 
ContextMenuHeading 
ContextMenuHeadingLinked 
ContextMenuHeadingTable 
ContextMenuHyperlink 
ContextMenuInk 
ContextMenuInkComment 
ContextMenuInlineActiveXControl 
ContextMenuInlineBusinessCard 
ContextMenuInlinePicture 
ContextMenuList 
ContextMenuListTable 
ContextMenuLockedReadingMode 
ContextMenuMailMergeBarcode 
ContextMenuNavigationPane 
ContextMenuObjectEditPoint 
ContextMenuObjectEditSegment 
ContextMenuObjectsGroup 
ContextMenuOfficePreviewHandlerWord 
ContextMenuOleObject 
ContextMenuOrganizationChart 
ContextMenuPageNumberingOptions 
ContextMenuPicture 
ContextMenuPictureTable 
ContextMenuReadOnlyMailHyperlink 
ContextMenuReadOnlyMailList 
ContextMenuReadOnlyMailListTable 
ContextMenuReadOnlyMailPictureTable 
ContextMenuReadOnlyMailTable 
ContextMenuReadOnlyMailTableCell 
ContextMenuReadOnlyMailTableWhole 
ContextMenuReadOnlyMailText 
ContextMenuReadOnlyMailTextTable 
ContextMenuRevision 
ContextMenuRichTextFont 
ContextMenuRichTextFontParagraph 
ContextMenuscriptAnchor 
ContextMenuShape 
ContextMenuShapeConnector 
ContextMenuShapeFreeform 
ContextMenuSmartArtBackground 
ContextMenuSmartArtContentPane 
ContextMenuSmartArtEdit1DShape 
ContextMenuSmartArtEdit1DShapeText 
ContextMenuSmartArtEditSmartArt 
ContextMenuSmartArtEditText 
ContextMenuSpell 
ContextMenuTable 
ContextMenuTableCell 
ContextMenuTableWhole 
ContextMenuTableWholeLinked 
ContextMenuText 
ContextMenuTextEdit 
ContextMenuTextEffect 
ContextMenuTextLinked 
ContextMenuTextTable 
ContextMenuXmlError 

선택된 Shape의 종류가 무엇인지는 Shape.Type 속성을 통해 알 수 있는데, 이에 대한 상숫값은 다음의 문서에 잘 나와 있습니다.

MsoShapeType Enumeration (Office)
; https://docs.microsoft.com/en-us/office/vba/api/Office.MsoShapeType




그나저나, 확장 add-in에 대한 역사가 깊어서 그런지 엄청난 수준으로 제어가 되는 것에 다소 놀라기도 했습니다. 그렇긴 한데, 너무 방대하다 보니 모든 부분에 세심하게 제어가 안 되는 것도 있습니다. 가령, 제가 원한 것은 PPT 파일에 .svg 파일을 포함한 경우 그 아이콘을 우 클릭해, ".wmf" 파일로 변환하는 확장을 만들고 싶었습니다.

custom_menu_on_shape_in_ppt_2.png

그래서, Ribbon.xml에 OLE 객체를 우 클릭했을 때 제가 원하는 메뉴를 넣었지만,

<contextMenu idMso="ContextMenuGraphicOleClassic">
    <button id="idCustomShow2" label="Convert to WMF" onAction="OnCustomShowFromSection" />
</contextMenu>

정작 해당 Shape에 대한 정보를 구하는 것에 실패했습니다.

public void OnCustomShowFromSection(Microsoft.Office.Core.IRibbonControl control)
{
    Selection selection = this.AddIn.Application.ActiveWindow.Selection;

    Shape shape = selection.ShapeRange[1];

    if (shape.Type == Office.MsoShapeType.msoEmbeddedOLEObject)
    { 
        string txt = null;

        try
        {
            string progId = shape.OLEFormat.ProgID; // progId == "Package"
        }
        catch (Exception e)
        {
            Console.WriteLine(txt + ": " + e.ToString());
        }
    }
}

progId == "Package"라는 정보를 제외하고, Shape가 표현하는 것이 ".svg" 파일인지에 대한 것조차 구할 수 없었습니다. 게다가 당연히 Embedding 객체이다 보니 파일 경로도 알 수 없었고 또한 그 객체의 바이너리 데이터를 접근하는 것도 할 수 없었습니다.

아쉽군요. ^^ PPT 확장으로 "svg to wmf" plug-in을 만들어 보고 싶었는데!

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 7/13/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 



2018-10-31 11시58분
정성태

... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12742정성태7/30/20217209개발 환경 구성: 585. Azure AD 인증을 위한 사용자 인증 유형
12741정성태7/29/20218358.NET Framework: 1082. Azure Active Directory - Microsoft Graph API 호출 방법파일 다운로드1
12740정성태7/29/20217054오류 유형: 747. SharePoint - InvalidOperationException 0x80131509
12739정성태7/28/20217014오류 유형: 746. Azure Active Directory - IDW10106: The 'ClientId' option must be provided.
12738정성태7/28/20217587오류 유형: 745. Azure Active Directory - Client credential flows must have a scope value with /.default suffixed to the resource identifier (application ID URI).
12737정성태7/28/20216551오류 유형: 744. Azure Active Directory - The resource principal named api://...[client_id]... was not found in the tenant
12736정성태7/28/20217043오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20217545.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202123482스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202110895.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216225오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217314개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20218850개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20217844.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/20217326.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/20218267.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/20218095VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/20216872오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/20219511개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/20217137오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/20217011오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/20217624오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/20216963Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/20216117오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/20216701개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/20216723Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
... 31  32  33  34  [35]  36  37  38  39  40  41  42  43  44  45  ...