Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [링크 복사], [링크+제목 복사]
조회: 15689
글쓴 사람
정성태 (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)
12620정성태4/29/202111908.NET Framework: 1052. C# - 왜 구조체는 16 바이트의 크기가 적합한가? [1]파일 다운로드1
12619정성태4/28/202112400.NET Framework: 1051. C# - 구조체의 크기가 16바이트가 넘어가면 힙에 할당된다? [2]파일 다운로드1
12618정성태4/27/202110959사물인터넷: 58. NodeMCU v1 ESP8266 CP2102 Module을 이용한 WiFi UDP 통신 [1]파일 다운로드1
12617정성태4/26/20218614.NET Framework: 1050. C# - ETW EventListener의 Keywords별 EventId에 따른 필터링 방법파일 다운로드1
12616정성태4/26/20218603.NET Framework: 1049. C# - ETW EventListener를 상속받았을 때 초기화 순서파일 다운로드1
12615정성태4/26/20216782오류 유형: 712. Microsoft Live 로그인 - 계정을 선택하는(Pick an account) 화면에서 진행이 안 되는 문제
12614정성태4/24/20219450개발 환경 구성: 570. C# - Azure AD 인증을 지원하는 ASP.NET Core/5+ 웹 애플리케이션 예제 구성 [4]파일 다운로드1
12613정성태4/23/20218521.NET Framework: 1048. C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (2) 관리 코드파일 다운로드1
12612정성태4/23/20218608.NET Framework: 1047. C# - ETW 이벤트의 Keywords에 속한 EventId 구하는 방법 (1) PInvoke파일 다운로드1
12611정성태4/22/20217906오류 유형: 711. 닷넷 EXE 실행 오류 - Mixed mode assembly is build against version 'v2.0.50727' of the runtime
12610정성태4/22/20217722.NET Framework: 1046. C# - 컴파일 시점에 참조할 수 없는 타입을 포함한 이벤트 핸들러를 Reflection을 이용해 구독하는 방법파일 다운로드1
12609정성태4/22/20219002.NET Framework: 1045. C# - 런타임 시점에 이벤트 핸들러를 만들어 Reflection을 이용해 구독하는 방법파일 다운로드1
12608정성태4/21/202110025.NET Framework: 1044. C# - Generic Host를 이용해 .NET 5로 리눅스 daemon 프로그램 만드는 방법 [9]파일 다운로드1
12607정성태4/21/20218550.NET Framework: 1043. C# - 실행 시점에 동적으로 Delegate 타입을 만드는 방법파일 다운로드1
12606정성태4/21/202112433.NET Framework: 1042. C# - enum 값을 int로 암시적(implicit) 형변환하는 방법? [2]파일 다운로드1
12605정성태4/18/20218516.NET Framework: 1041. C# - AssemblyID, ModuleID를 관리 코드에서 구하는 방법파일 다운로드1
12604정성태4/18/20217301VS.NET IDE: 163. 비주얼 스튜디오 속성 창의 "Build(빌드)" / "Configuration(구성)"에서의 "활성" 의미
12603정성태4/16/20218137VS.NET IDE: 162. 비주얼 스튜디오 - 상속받은 컨트롤이 디자인 창에서 지원되지 않는 문제
12602정성태4/16/20219328VS.NET IDE: 161. x64 DLL 프로젝트의 컨트롤이 Visual Studio의 Designer에서 보이지 않는 문제 [1]
12601정성태4/15/20218439.NET Framework: 1040. C# - REST API 대신 github 클라이언트 라이브러리를 통해 프로그래밍으로 접근
12600정성태4/15/20218631.NET Framework: 1039. C# - Kubeconfig의 token 설정 및 인증서 구성을 자동화하는 프로그램
12599정성태4/14/20219333.NET Framework: 1038. C# - 인증서 및 키 파일로부터 pfx/p12 파일을 생성하는 방법파일 다운로드1
12598정성태4/14/20219473.NET Framework: 1037. openssl의 PEM 개인키 파일을 .NET RSACryptoServiceProvider에서 사용하는 방법 (2)파일 다운로드1
12597정성태4/13/20219482개발 환경 구성: 569. csproj의 내용을 공통 설정할 수 있는 Directory.Build.targets / Directory.Build.props 파일
12596정성태4/12/20219274개발 환경 구성: 568. Windows의 80 포트 점유를 해제하는 방법
12595정성태4/12/20218678.NET Framework: 1036. SQL 서버 - varbinary 타입에 대한 문자열의 CAST, CONVERT 변환을 C# 코드로 구현
... 31  32  33  34  35  36  37  38  39  [40]  41  42  43  44  45  ...