有关详细文章,请查看此MSDN 杂志链接。
我使用那里的示例代码为您创建了一个快速片段,以便在给定笔记本的给定部分中创建一个新页面。
如果您使用的是 Visual Studio 2010,文章中列出了几个“陷阱”:
首先,由于 Visual Studio 2010 附带的 OneNote 互操作程序集不匹配,您不应直接
在“添加引用”对话框的 .NET 选项卡上引用 Microsoft.Office.Interop.OneNote 组件,而应引用 Microsoft OneNote 14.0 COM 选项卡上的类型库组件。这仍会导致将 OneNote 互操作程序集添加到项目的引用中。
其次,OneNote 14.0 类型库与 Visual Studio 2010 的“NOPIA”功能不兼容(默认情况下,主互操作程序集不嵌入应用程序中)。因此,请确保将 OneNote 互操作程序集引用的 Embed Interop Types 属性设置为 False。
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;
}
}
}