如需详细文章,请查看MSDN Magazine链接。
我使用那里的示例代码为您创建了一个快速片段,以便在给定笔记本中的给定部分中创建新页面。
如果您正在使用Visual Studio 2010,则文章中列出了一些“要点”:
首先,由于与Visual Studio 2010一起发布的OneNote互操作程序集不匹配,因此您不应直接引用“添加引用”对话框上.NET选项卡上的Microsoft.Office.Interop.OneNote组件,而应引用COM选项卡上的Microsoft OneNote 14.0类型库组件。这仍会导致将OneNote互操作程序集添加到项目的引用中。
其次,OneNote 14.0类型库与Visual Studio 2010的“NOPIA”功能不兼容(默认情况下不嵌入主互操作程序集)。因此,请确保将Interop类型嵌入属性设置为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)
{
string pageId;
onenoteApp.CreateNewPage(sectionId, out pageId, NewPageStyle.npsBlankPageWithTitle);
string xml;
onenoteApp.GetPageContent(pageId, out xml, PageInfo.piAll);
var doc = XDocument.Parse(xml);
var title = doc.Descendants(ns + "T").First();
title.Value = pageName;
onenoteApp.UpdatePageContent(doc.ToString());
return pageId;
}
}
}