Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [링크 복사], [링크+제목 복사]
조회: 15697
글쓴 사람
정성태 (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)
12572정성태3/22/20219210.NET Framework: 1029. C# - GC 호출로 인한 메모리 압축(Compaction)을 확인하는 방법파일 다운로드1
12571정성태3/21/20218376오류 유형: 706. WSL 2 기반으로 "Enable Kubernetes" 활성화 시 초기화 실패 [1]
12570정성태3/19/202112689개발 환경 구성: 555. openssl - CA로부터 인증받은 새로운 인증서를 생성하는 방법
12569정성태3/18/202111563개발 환경 구성: 554. WSL 인스턴스 export/import 방법 및 단축 아이콘 설정 방법
12568정성태3/18/20217262오류 유형: 705. C# 빌드 - Couldn't process file ... due to its being in the Internet or Restricted zone or having the mark of the web on the file.
12567정성태3/17/20218588개발 환경 구성: 553. Docker Desktop for Windows를 위한 k8s 대시보드 활성화 [1]
12566정성태3/17/20218931개발 환경 구성: 552. Kubernetes - kube-apiserver와 REST API 통신하는 방법 (Docker Desktop for Windows 환경)
12565정성태3/17/20216443오류 유형: 704. curl.exe 실행 시 dll not found 오류
12564정성태3/16/20216938VS.NET IDE: 160. 새 프로젝트 창에 C++/CLI 프로젝트 템플릿이 없는 경우
12563정성태3/16/20218891개발 환경 구성: 551. C# - JIRA REST API 사용 정리 (3) jira-oauth-cli 도구를 이용한 키 관리
12562정성태3/15/20219985개발 환경 구성: 550. C# - JIRA REST API 사용 정리 (2) JIRA OAuth 토큰으로 API 사용하는 방법파일 다운로드1
12561정성태3/12/20218607VS.NET IDE: 159. Visual Studio에서 개행(\n, \r) 등의 제어 문자를 치환하는 방법 - 정규 표현식 사용
12560정성태3/11/20219953개발 환경 구성: 549. ssh-keygen으로 생성한 개인키/공개키 파일을 각각 PKCS8/PEM 형식으로 변환하는 방법
12559정성태3/11/20219346.NET Framework: 1028. 닷넷 5 환경의 Web API에 OpenAPI 적용을 위한 NSwag 또는 Swashbuckle 패키지 사용 [2]파일 다운로드1
12558정성태3/10/20218867Windows: 192. Power Automate Desktop (Preview) 소개 - Bitvise SSH Client 제어 [1]
12557정성태3/10/20217503Windows: 191. 탐색기의 보안 탭에 있는 "Object name" 경로에 LEFT-TO-RIGHT EMBEDDING 제어 문자가 포함되는 문제
12556정성태3/9/20216791오류 유형: 703. PowerShell ISE의 Debug / Toggle Breakpoint 메뉴가 비활성 상태인 경우
12555정성태3/8/20218789Windows: 190. C# - 레지스트리에 등록된 DigitalProductId로부터 라이선스 키(Product Key)를 알아내는 방법파일 다운로드2
12554정성태3/8/20218629.NET Framework: 1027. 닷넷 응용 프로그램을 위한 PDB 옵션 - full, pdbonly, portable, embedded
12553정성태3/5/20219101개발 환경 구성: 548. 기존 .NET Framework 프로젝트를 .NET Core/5+ 용으로 변환해 주는 upgrade-assistant, try-convert 도구 소개 [4]
12552정성태3/5/20218366개발 환경 구성: 547. github workflow/actions에서 Visual Studio Marketplace 패키지 등록하는 방법
12551정성태3/5/20217271오류 유형: 702. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly. (2)
12550정성태3/5/20216980오류 유형: 701. Live Share 1.0.3713.0 버전을 1.0.3884.0으로 업데이트 이후 ContactServiceModelPackage 오류 발생하는 문제
12549정성태3/4/20217422오류 유형: 700. VsixPublisher를 이용한 등록 시 다양한 오류 유형 해결책
12548정성태3/4/20218198개발 환경 구성: 546. github workflow/actions에서 nuget 패키지 등록하는 방법
12547정성태3/3/20218699오류 유형: 699. 비주얼 스튜디오 - The 'CascadePackage' package did not load correctly.
... 31  32  33  34  35  36  37  38  39  40  41  [42]  43  44  45  ...