Microsoft MVP성태의 닷넷 이야기
개발 환경 구성: 314. C# - PowerPoint 확장 Add-in 만드는 방법 [링크 복사], [링크+제목 복사]
조회: 15690
글쓴 사람
정성태 (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분
정성태

... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...
NoWriterDateCnt.TitleFile(s)
12445정성태12/8/20208433오류 유형: 692. C# Marshal.PtrToStructure - The structure must not be a value class.파일 다운로드1
12444정성태12/8/20209230.NET Framework: 978. C# - GUID 타입 전용의 UnmanagedType.LPStruct [1]파일 다운로드1
12443정성태12/8/20209013.NET Framework: 977. C# PInvoke - C++의 매개변수에 대한 마샬링을 tlbexp.exe를 이용해 확인하는 방법
12442정성태12/4/20207994오류 유형: 691. Visual Studio - Build Events에 robocopy를 사용할때 "Invalid Parameter #1" 오류가 발행하는 경우
12441정성태12/4/20207662오류 유형: 690. robocopy - ERROR : No Destination Directory Specified.
12440정성태12/4/20208689오류 유형: 689. SignTool Error: Invalid option: /as
12439정성태12/4/20209902디버깅 기술: 176. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우 (2) [1]
12438정성태12/2/20209879오류 유형: 688. .Visual C++ - Error C2011 'sockaddr': 'struct' type redefinition
12437정성태12/1/20209482VS.NET IDE: 155. pfx의 암호 키 파일을 Visual Studio 없이 등록하는 방법
12436정성태12/1/20209798오류 유형: 687. .NET Core 2.2 빌드 - error MSB4018: The "RazorTagHelper" task failed unexpectedly.
12435정성태12/1/202015234Windows: 181. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (4) - ReuseUnicastPort를 이용한 포트 고갈 문제 해결 [1]파일 다운로드1
12434정성태11/30/202010530Windows: 180. C# - dynamicport 값의 범위를 알아내는 방법
12433정성태11/29/20209602Windows: 179. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (3) - SO_PORT_SCALABILITY파일 다운로드1
12432정성태11/29/202011057Windows: 178. 윈도우 환경에서 클라이언트 소켓의 최대 접속 수 (2) - SO_REUSEADDR [1]파일 다운로드1
12431정성태11/27/20208988.NET Framework: 976. UnmanagedCallersOnly + C# 9.0 함수 포인터 사용 시 x86 빌드에서 오동작하는 문제파일 다운로드1
12430정성태11/27/20209674오류 유형: 686. Ubuntu - E: The repository 'cdrom://...' does not have a Release file.
12429정성태11/25/20209770디버깅 기술: 175. windbg - 특정 Win32 API에서 BP가 안 걸리는 경우
12428정성태11/25/20208738VS.NET IDE: 154. Visual Studio - .NET Core App 실행 시 dotnet.exe 실행 화면만 나오는 문제
12427정성태11/24/20209852.NET Framework: 975. .NET Core를 직접 호스팅해 (runtimeconfig.json 없이) EXE만 배포해 실행파일 다운로드1
12426정성태11/24/20208487오류 유형: 685. WinDbg Preview - error InitTypeRead
12425정성태11/24/20209513VC++: 141. Visual C++ - "Treat Warnings As Errors" 옵션이 꺼져 있는데도 일부 경고가 에러 처리되는 경우
12424정성태11/24/20209928VC++: 140. C++의 연산자 동의어(operator synonyms), 대체 토큰 [1]
12423정성태11/22/202010852.NET Framework: 974. C# 9.0 - (16) 제약 조건이 없는 형식 매개변수 주석(Unconstrained type parameter annotations)파일 다운로드1
12422정성태11/21/20208671.NET Framework: 973. .NET 5, .NET Framework에서만 허용하는 UnmanagedCallersOnly 사용예파일 다운로드1
12421정성태11/19/20208423.NET Framework: 972. DNNE가 출력한 NE DLL을 직접 생성하는 방법파일 다운로드1
12420정성태11/19/20207620오류 유형: 684. Visual C++ - MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
... 46  [47]  48  49  50  51  52  53  54  55  56  57  58  59  60  ...