In my user control, I used webbrowser element as rich text editor. When pressed Ctrl+F
a winform is shown and you can type searching. But every user may not know Ctrl+F
to make search. Therefore I added an icon for searching to toolStrip menu. But I don't know what I code in the SearchButton_Click
event to show search form as if clicked Ctrl+F
.
Asked
Active
Viewed 1,990 times
3

Reza Aghaei
- 120,393
- 18
- 203
- 398
2 Answers
3
You can send commands to the hosted web control using the IOleCommandTarget. It's supposed to be equivalent to HtmlDocument.ExecCommand method but for some reason, some commands don't work in the later.
The command you're after is IDM_FIND.
Here is some C# code to run it:
private void SearchButton_Click(object sender, EventArgs e)
{
dynamic ax = webBrowser1.ActiveXInstance;
// IHtmlDocument2 also implements IOleCommandTarget
var qi = (IOleCommandTarget)ax.Document;
// MSHTML commands group
var CGID_MSHTML = new Guid("de4ba900-59ca-11cf-9592-444553540000");
const int IDM_FIND = 67;
qi.Exec(CGID_MSHTML, IDM_FIND, 0, null, null);
}
[Guid("b722bccb-4e68-101b-a2bc-00aa00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public interface IOleCommandTarget
{
void NotDefinedHere(); // don't remove this
[PreserveSig]
int Exec([MarshalAs(UnmanagedType.LPStruct)] Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object pvaIn, [In, Out] object pvaOut);
}

Simon Mourier
- 132,049
- 21
- 248
- 298
-
Hohayda... Thank you very much for the marvelous answer. This was an inextricable problem for me. – Mar 05 '18 at 09:09
-
webbrowser1 is giving error (the name does not exist). I am using ASP.net and C# – Shomaail Dec 06 '18 at 10:50
-
@shomaail - please ask another question, it sounds like a compilation problem. – Simon Mourier Dec 06 '18 at 10:57
-
@simon I found my question here https://stackoverflow.com/questions/8080217/use-browser-search-ctrlf-through-a-button-in-website – Shomaail Dec 06 '18 at 11:24
3
As another simple option, you can simply send Ctrl+F to the WebBrowser
:
private void findToolStripButton_Click(object sender, EventArgs e)
{
webBrowser1.Focus();
SendKeys.Send("^f");
}

Reza Aghaei
- 120,393
- 18
- 203
- 398
-
1
-
webbrowser1 is giving error (the name does not exist). I am using ASP.net and C# – Shomaail Dec 06 '18 at 10:49
-
@shomaail It's a Windows Forms question, and `webBrowser1` points to an instance of `WebBrowser` control which you have dropped on the form. It has nothing to do with ASP.NET. – Reza Aghaei Dec 06 '18 at 11:13