Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [링크 복사], [링크+제목 복사]
조회: 15692
글쓴 사람
정성태 (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)
12520정성태1/30/20218244개발 환경 구성: 526. 오라클 클라우드의 VM에 ping ICMP 여는 방법
12519정성태1/30/20217375개발 환경 구성: 525. 오라클 클라우드의 VM을 외부에서 접근하기 위해 포트 여는 방법
12518정성태1/30/202124822Linux: 37. Ubuntu에 Wireshark 설치 [2]
12517정성태1/30/202112385Linux: 36. 윈도우 클라이언트에서 X2Go를 이용한 원격 리눅스의 GUI 접속 - 우분투 20.04
12516정성태1/29/20219041Windows: 188. Windows - TCP default template 설정 방법
12515정성태1/28/202110210웹: 41. Microsoft Edge - localhost에 대해 http 접근 시 무조건 https로 바뀌는 문제 [3]
12514정성태1/28/202110548.NET Framework: 1021. C# - 일렉트론 닷넷(Electron.NET) 소개 [1]파일 다운로드1
12513정성태1/28/20218580오류 유형: 698. electronize - User Profile 디렉터리에 공백 문자가 있는 경우 빌드가 실패하는 문제 [1]
12512정성태1/28/20218396오류 유형: 697. The program can't start because VCRUNTIME140.dll is missing from your computer. Try reinstalling the program to fix this problem.
12511정성태1/27/20218131Windows: 187. Windows - 도스 시절의 8.3 경로를 알아내는 방법
12510정성태1/27/20218500.NET Framework: 1020. .NET Core Kestrel 호스팅 - Razor 지원 추가 [1]파일 다운로드1
12509정성태1/27/20219473개발 환경 구성: 524. Jupyter Notebook에서 C#(F#, PowerShell) 언어 사용을 위한 환경 구성 [3]
12508정성태1/27/20218080개발 환경 구성: 523. Jupyter Notebook - Slide 플레이 버튼이 없는 경우
12507정성태1/26/20218188VS.NET IDE: 157. Visual Studio - Syntax Visualizer 메뉴가 없는 경우
12506정성태1/25/202111426.NET Framework: 1019. Microsoft.Tye 기본 사용법 소개 [1]
12505정성태1/23/20219233.NET Framework: 1018. .NET Core Kestrel 호스팅 - Web API 추가 [1]파일 다운로드1
12504정성태1/23/202110355.NET Framework: 1017. .NET 5에서의 네트워크 라이브러리 개선 (2) - HTTP/2, HTTP/3 관련 [1]
12503정성태1/21/20218607오류 유형: 696. C# - HttpClient: Requesting HTTP version 2.0 with version policy RequestVersionExact while HTTP/2 is not enabled.
12502정성태1/21/20219332.NET Framework: 1016. .NET Core HttpClient의 HTTP/2 지원파일 다운로드1
12501정성태1/21/20218407.NET Framework: 1015. .NET 5부터 HTTP/1.1, 2.0 선택을 위한 HttpVersionPolicy 동작 방식파일 다운로드1
12500정성태1/21/20218987.NET Framework: 1014. ASP.NET Core(Kestrel)의 HTTP/2 지원 여부파일 다운로드1
12499정성태1/20/202110209.NET Framework: 1013. .NET Core Kestrel 호스팅 - 포트 변경, non-localhost 접속 지원 및 https 등의 설정 변경 [1]파일 다운로드1
12498정성태1/20/20219155.NET Framework: 1012. .NET Core Kestrel 호스팅 - 비주얼 스튜디오의 Kestrel/IIS Express 프로파일 설정
12497정성태1/20/202110052.NET Framework: 1011. C# - OWIN Web API 예제 프로젝트 [1]파일 다운로드2
12496정성태1/19/20218921.NET Framework: 1010. .NET Core 콘솔 프로젝트에서 Kestrel 호스팅 방법 [1]
12495정성태1/19/202111045웹: 40. IIS의 HTTP/2 지원 여부 - h2, h2c [1]
... 31  32  33  34  35  36  37  38  39  40  41  42  43  [44]  45  ...