【问题标题】:Move my cursor to the end of the Text in MsWord using C#?使用 C# 将光标移动到 MsWord 中文本的末尾?
【发布时间】:2012-08-22 05:17:51
【问题描述】:
这个问题可能听起来很简单,但我找不到任何解决方案。我想做的是将 MsWord 中的光标位置移动到文本的末尾。我的代码如下
object StartPos = 0;
object Endpos = 1;
Microsoft.Office.Interop.Word.Range rng= oDoc.Range(ref StartPos, ref Endpos);
rng.Text = "This is first line Word from C#";
输出是
我这是 C# 的第一行字
但是我想要这样的东西
这是 C# 中的第一行字 I
谢谢大家
【问题讨论】:
标签:
c#
visual-studio
ms-word
【解决方案1】:
谢谢大家的回复我似乎找到了一个简单的解决方案。我尝试修改哈桑的解决方案。可能有一个更简单的方法,但到目前为止我已经找到了这个
object NewEndPos = rng.StoryLength-1;
rng = oDoc.Range(ref NewEndPos, ref NewEndPos);
rng.Select();
【解决方案2】:
这个怎么样?这与按 Ctrl-Shift-End 相同。请注意,word 是单词应用程序,而不是文档。假定已经选择了正确的活动文档。
word.Selection.EndKey(WdUnits.wdStory);
【解决方案3】:
rng= oDoc.Range(ref Endpos, ref Endpos);
rng.Select();
【解决方案4】:
Similar question - Position cursor at start/end of Word document
该答案更详细地介绍了which 和what。答案在 c# 和 vb 之间混杂在一起,所以我在这里包含 另一个答案,它使用了一种稍微不同的方法来转到文档的最后一部分。
我的两分钱:
//vb does this kind of thing for them
//but in c# we need an object we can pretend is null
object oMissing = System.Reflection.Missing.Value;
//Start Word and create a new document.
Word._Application oWord;
Word._Document oDoc; //whenever i read this i think 'hodor'
oWord = new Word.Application();
oWord.Visible = true;
oDoc = oWord.Documents.Add(ref oMissing, ref oMissing,
ref oMissing, ref oMissing);
object StartPos = 0;
object Endpos = 1;
Microsoft.Office.Interop.Word.Range rng = oDoc.Range(ref StartPos, ref Endpos);
rng.Text = "This is first line Word from C#";
//object what = Word.WdGoToItem.wdGoToLine;
//I couldn't get wdGoToLine to work but wdGoToPercent was happy
object what = Word.WdGoToItem.wdGoToPercent;
object which = Word.WdGoToDirection.wdGoToLast;
oWord.Selection.GoTo(ref what, ref which, oMissing, oMissing);
此方法略有不同,它不会告诉 word 将光标移动到最后一行,而是文档的最后一个 percentage,我将不得不假设为 100。那将是单行文档中的行尾,但如果光标位于第一行(开头)并且我们告诉 Word 转到最后一行,则什么也不会发生:我们已经在那里,在 开始 最后一行。
【解决方案5】:
试试这个方法:
oDoc.GoTo(ref what, ref which, ref missing, ref missing);