我正在尝试实现搜索例程:在Webbrowser中查找Next和Find Previous。我知道里面有内置查找对话框,但我不想使用它。相反,我正在努力编写自己的例程,但我无法通过。以下代码很好地实现了“查找下一个”:
using mshtml;
....
private void toolStripButton5_Click(object sender, EventArgs e)
{
IHTMLDocument2 htmlDocument = WB.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject sel = (IHTMLSelectionObject)htmlDocument.selection;
IHTMLTxtRange tr = (IHTMLTxtRange)sel.createRange() as IHTMLTxtRange;
string s = toolStripTextBox1.Text;
tr.collapse(false);
tr.findText(s, 1, 0); // positive value, should search forward, negative backward
tr.select();
}
我完全无助地制作“找到以前的”例程。任何天才都可以锻造吗? (它可能与上面的非常相似)。
非常感谢
答案 0 :(得分:1)
对于“查找上一个”例程,请使用相同的代码并进行两次修改: 1)将tr.collapse的参数从false更改为true; 2)将tr.findText的第二个参数从1更改为-1。
所以这些行将如下:
tr.collapse(true); // use true to move caret at the beginning of the current selection
tr.findText(s, -1, 0); // positive value, should search forward, negative backward
答案 1 :(得分:0)
IHTMLTxtRange tmprange; private void Find(int Direction,bool Collapse) {
IHTMLDocument2 htmlDocument = browser.Document.DomDocument as IHTMLDocument2;
IHTMLSelectionObject sel = (IHTMLSelectionObject)htmlDocument.selection;
IHTMLTxtRange tr = (IHTMLTxtRange)sel.createRange() as IHTMLTxtRange;
string s = textBoxFindData.Text;
if (tmprange == null)
{
tr.collapse(Collapse);
tmprange = tr;
tr.findText(s, Direction, 0); // positive value, should search forward, negative backward
if (tr.text == null)
{
MessageBox.Show("Can not find string " + "[" + s + "]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
tr.select();
}
else
{
tmprange.collapse(Collapse);
tmprange.findText(s, Direction, 0); // positive value, should search forward, negative backward
if (tmprange.text == null)
{
MessageBox.Show("Can not find string " + "[" + s + "]", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
tmprange.select();
}
}
private void buttonPrevious_Click(object sender, EventArgs e)
{
Find(-1, true);
}