Carlos Delgado在ourcodeworld.com上有一篇精彩的文章,其中介绍了如何修改上下文菜单:
我用他的示例将这些项目添加到上下文菜单:
public class MyCustomMenuHandler : IContextMenuHandler
{
public void OnBeforeContextMenu(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, IMenuModel model)
{
// Remove any existent option using the Clear method of the model
//
//model.Clear();
Console.WriteLine("Context menu opened !");
// You can add a separator in case that there are more items on the list
if (model.Count > 0)
{
model.AddSeparator();
}
// Add a new item to the list using the AddItem method of the model
model.AddItem((CefMenuCommand)26501, "Show DevTools");
// Add a separator
model.AddSeparator();
model.AddItem((CefMenuCommand)26503, "Open in Paintbrush");
model.AddItem((CefMenuCommand)26504, "Open in Excel");
model.AddItem((CefMenuCommand)26505, "Run Script..");
......等
然后删除了查看源代码选项:
model.Remove((CefMenuCommand)132); // View Source
然后只是为了好玩而加入了这些选项,这些选项默认情况下不在菜单中:
model.AddItem((CefMenuCommand)113, "Copy");
model.AddItem((CefMenuCommand)100, "Back");
model.AddItem((CefMenuCommand)101, "Forward");
model.AddItem((CefMenuCommand)102, "Reload");
model.AddItem((CefMenuCommand)103, "Reload No Cache");
model.AddItem((CefMenuCommand)131, "Print");
然后玩得开心
public void SaveImage(string imageUrl, string filename, ImageFormat format)
{
System.Net.WebClient client = new WebClient();
System.IO.Stream stream = client.OpenRead(imageUrl);
Bitmap bitmap; bitmap = new Bitmap(stream);
if (bitmap != null)
{
bitmap.Save(filename, format);
}
stream.Flush();
stream.Close();
client.Dispose();
}
public bool OnContextMenuCommand(IWebBrowser browserControl, IBrowser browser, IFrame frame, IContextMenuParams parameters, CefMenuCommand commandId, CefEventFlags eventFlags)
{
if (commandId == (CefMenuCommand)26501)
{
browser.GetHost().ShowDevTools();
return true;
}
if (commandId == (CefMenuCommand)26502)
{
browser.GetHost().CloseDevTools();
return true;
}
if (commandId == (CefMenuCommand)113) // Copy
{
if (parameters.LinkUrl.Length > 0)
{
Clipboard.SetText(parameters.LinkUrl);
}
if (parameters.MediaType == ContextMenuMediaType.Image )
{
Clipboard.SetText(parameters.SourceUrl);
}
}
if (commandId == (CefMenuCommand)26503) // Open in paintbrush
{
if (parameters.LinkUrl.Length > 0) {
Clipboard.SetText(parameters.LinkUrl);
}
if (parameters.MediaType == ContextMenuMediaType.Image)
{
Clipboard.SetText(parameters.SourceUrl);
string subPath = @"C:\temp";
string fn = @"C:\temp\temp.bmp";
System.IO.Directory.CreateDirectory(subPath);
SaveImage(parameters.SourceUrl, fn, ImageFormat.Bmp);
Process.Start(fn);
}
}
// React to the third ID (Display alert message)
if (commandId == (CefMenuCommand)26503)
{
MessageBox.Show("An example alert message ?");
return true;
}
// Any new item should be handled through a new if statement
// Return false should ignore the selected option of the user !
return false;
}