如需详细文章,请查看MSDN Magazine link。
我使用那里的示例代码创建了一个快速的 sn-p,以便您在给定笔记本的给定部分中创建一个新页面。
如果您使用的是 Visual Studio 2010,文章中列出了几个“陷阱”:
首先,由于随附的 OneNote 互操作程序集不匹配
对于 Visual Studio 2010,您不应直接引用
添加的 .NET 选项卡上的 Microsoft.Office.Interop.OneNote 组件
参考对话框,而是参考 Microsoft OneNote 14.0
COM 选项卡上的类型库组件。这仍然导致
将 OneNote 互操作程序集添加到项目的引用中。
其次,OneNote 14.0 类型库不兼容
Visual Studio 2010 “NOPIA”功能(其中主要互操作
默认情况下,程序集不嵌入到应用程序中)。所以,
确保将 Embed Interop Types 属性设置为 False
OneNote 互操作程序集参考。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using Microsoft.Office.Interop.OneNote;
namespace OneNote
{
class Program
{
static Application onenoteApp = new Application();
static XNamespace ns = null;
static void Main(string[] args)
{
GetNamespace();
string notebookId = GetObjectId(null, HierarchyScope.hsNotebooks, "Tasks");
string sectionId = GetObjectId(notebookId, HierarchyScope.hsSections, "Notes");
string pageId = CreatePage(sectionId, "Test");
}
static void GetNamespace()
{
string xml;
onenoteApp.GetHierarchy(null, HierarchyScope.hsNotebooks, out xml);
var doc = XDocument.Parse(xml);
ns = doc.Root.Name.Namespace;
}
static string GetObjectId(string parentId, HierarchyScope scope, string objectName)
{
string xml;
onenoteApp.GetHierarchy(parentId, scope, out xml);
var doc = XDocument.Parse(xml);
var nodeName = "";
switch (scope)
{
case (HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
case (HierarchyScope.hsPages): nodeName = "Page"; break;
case (HierarchyScope.hsSections): nodeName = "Section"; break;
default:
return null;
}
var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();
return node.Attribute("ID").Value;
}
static string CreatePage(string sectionId, string pageName)
{
// Create the new page
string pageId;
onenoteApp.CreateNewPage(sectionId, out pageId, NewPageStyle.npsBlankPageWithTitle);
// Get the title and set it to our page name
string xml;
onenoteApp.GetPageContent(pageId, out xml, PageInfo.piAll);
var doc = XDocument.Parse(xml);
var title = doc.Descendants(ns + "T").First();
title.Value = pageName;
// Update the page
onenoteApp.UpdatePageContent(doc.ToString());
return pageId;
}
}
}