Deactivate Middle Mouse Button Move in Windows Browser Form - c#

I got a WebBrowser Control in a Windows Form and i want to use the middle mouse button click to add a new tab to my Browser. The only problem is that everytime i use the middle mouse button, the arrows to move the page appear.
So how can i disable this move/drag command only for the clicks on my links?

try this:
There are two different parts to this solution. The first is pretty easy - just set an event handler for the MouseDown event of your browser control:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (webBrowser1.Document != null)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
}
private void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
e.ReturnValue = false;
// Your custom code
}
}
but there were also some javascript-heavy websites on which this solution did not work. For those, I found another solution involving injecting javascript into the document which will prevent the middle-click:
HtmlElement head = browser.Document.GetElementsByTagName("head")[0];
HtmlElement mscript = browser.Document.CreateElement("script");
IHTMLScriptElement element = (IHTMLScriptElement)mscript.DomElement;
element.text = "function handleMouseEvent(e) { "
+ "var evt = (e==null ? event:e); "
+ "if ( e.which == 2 ) e.preventDefault(); "
+ "return true; } "
+ "document.onmousedown = handleMouseEvent; "
+ "document.onmouseup = handleMouseEvent; "
+ "document.onclick = handleMouseEvent; ";
head.AppendChild(mscript);
UPDATE
The JavaScript injection methodology can be improved by following the suggested way to do it using managed code only:
stackoverflow.com/a/6222430/1248295
This is an alternative example implementation of the javascript injection, wrote in VB.NET:
Private ReadOnly handleMouseEventJs As String =
"
function HandleMouseEvent(e) {
var evt = (e==null ? event:e);
if (e.which == 2) e.preventDefault();
return true;
}
document.onmousedown = HandleMouseEvent;
// These events below seems are not necessary to handle for this purpose.
// document.onmouseup = HandleMouseEvent;
// document.onclick = HandleMouseEvent;
"
Private Sub WebBrowser1_Navigated(sender As Object, e As WebBrowserNavigatedEventArgs) _
Handles WebBrowser1.Navigated
Dim wb As WebBrowser = DirectCast(sender, WebBrowser)
Dim doc As HtmlDocument = wb.Document
Dim head As HtmlElement = doc.GetElementsByTagName("head")(0)
Dim js As HtmlElement = doc.CreateElement("script")
js.SetAttribute("text", handleMouseEventJs)
head.AppendChild(js)
' This method call seems not necessary at all, it works fine without invocking it.
' doc.InvokeScript("HandleMouseEvent", Nothing)
End Sub
UPDATE 2
Inject this code instead:
document.body.onmousedown = function(e) { if (e.button === 1) return false; }
https://stackoverflow.com/a/30423534/1248295

The move icon displayed upon middle mouse click is under control of your mouse settings. But you can detect middle mouse click on your WebBrowser control.
Register DocumentCompleted event for your WebBrowser control and use the following code:
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
webBrowser1.Document.MouseDown += Document_MouseDown;
}
void Document_MouseDown(object sender, HtmlElementEventArgs e)
{
if (e.MouseButtonsPressed == System.Windows.Forms.MouseButtons.Middle)
{
// code to add tab or do sth else
}
}

Related

Why is my button's click event not firing?

I have two Buttons on my Sharepoint 2010 Web Page. One fires (server-side), the other doesn't*. They are set up similarly. Here is the one that does fire:
Button btnSave = new Button();
btnSave.Text = "Save";
btnSave.Click += new EventHandler(btnSave_Click);
this.Controls.Add(btnSave);
. . .
private void btnSave_Click(object sender, EventArgs e)
{
LiteralControl message = null; // this breakpoint is hit, sho' nuff
. . . // code elided for brevity
}
...and here is the one that isn't invoked:
Button btnGeneratePDF = null;
. . .
btnGeneratePDF = new Button();
btnGeneratePDF.Text = "Generate PDF";
btnGeneratePDF.UseSubmitBehavior = true; // trying this after it didn't work without it... (still doesn't work)
btnGeneratePDF.Click += new EventHandler(btnGenPDF_Click);
this.Controls.Add(btnGeneratePDF);
private void btnGenPDF_Click(object sender, EventArgs e)
{
GeneratePDF(listOfListItems); // breakpoint here never reached
}
Why is btnSave's handler invoked when I click it, but btnGeneratePDF's handler is not?
I can get buttons to fire client-side (jQuery) by using HtmlButtons, but I need this one to fire server-side/C#.
UPDATE
Would the fact that I'm creating the pdfgen button inside the click handler of the other Button have anything to do with this? Here's the significant part of that:
private void btnSave_Click(object sender, EventArgs e)
{
try
{
. . . relatively insignificant code elided for brevity
Button btnGeneratePDF = new Button();
btnGeneratePDF.Text = "Generate PDF";
btnGeneratePDF.UseSubmitBehavior = true; // trying this after it didn't
work without it...still doesn't work; don't know why - configuration of this
button is the same as for btnSave
btnGeneratePDF.Click += new EventHandler(btnGenPDF_Click);
this.Controls.Add(btnGeneratePDF);
. . . relatively insignificant code elided for brevity
?
UPDATE 2
Only the first (btnSave) button (and not the identically-created btnGeneratePDF button) is marked as type="submit":
<input type="submit" name="ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl152" value="Save" onclick="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions("ctl00$ctl24$g_5f3fedca_19f7_4bc3_b84e_efbef0c48a33$ctl00$ctl152", "", true, "", "", false, false))" />
I believe only one button of type submit is allowed, but I tried to shove btnSave out of the way when I was done with it by setting its Enabled property to false, but that did nothing (good).
You must recreate the dynamic control in page processing. Here is an example of how to do it:
protected void Page_Load(object sender, EventArgs e)
{
Button b = new Button();
b.ID = "one";
b.Text = "one";
b.Click += B_Click;
this.form1.Controls.Add(b);
// this is where the dynamic control is created if id is in postback
if (Request["two"] != null)
{
Button x = new Button();
x.ID = "two";
x.Text = "two";
x.Click += X_Click;
this.form1.Controls.Add(x);
}
}
private void B_Click(object sender, EventArgs e)
{
Button x = new Button();
x.ID = "two";
x.Text = "two";
x.Click += X_Click;
this.form1.Controls.Add(x);
LabelOutput.Text += " ...one";
}
private void X_Click(object sender, EventArgs e)
{
LabelOutput.Text += " ...two";
}
If you assign the click event handler of the "pdf" button inside the click event of the Save button means that the PDF button is dynamically created and its click event assigned each time you press click on the save button. Only at that time the pdf will get its event assigned.
This is how I got it to work:
0) Declare button at the top:
Button btnGeneratePDF = null;
1) Create and configure it within the Page_Load() event (as suggested by Michael Palermo)
btnGeneratePDF = new Button();
btnGeneratePDF.Text = "Generate PDF";
btnGeneratePDF.UseSubmitBehavior = true; // I don't know if this is necessary
btnGeneratePDF.Click += new EventHandler(btnGenPDF_Click);
btnGeneratePDF.Visible = false;
this.Controls.Add(btnGeneratePDF);
Note that visible is set to false at first
2) Make the "Generate PDF" button visible within the "btnSave" click handler:
btnGeneratePDF.Visible = true;
That's it - it works fine now.

image control with radio buttons

I need a control which can hold an image and two radio buttons, like the one we have when we upload a pictures on fb / orkut.
1. Image
2. Delete radio button.
3. Cover radio button.[Set this image as cover of album]
i have created a user control with these three things.
On my aspx page on click of a button i need to add this user control.
Means, user will select the image using FileUpload and when he clicks on the button this user control should be loaded.
I am able to load the control. Check the following code.
<code>
<pre lang="cs">
protected void btnAddURL_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
//ItemList is an array list used to store the filename.
ItemList.Add(FileUpload1.FileName);
showImage();
}
}</pre>
public void showImage()
{
PlaceHolder p = new PlaceHolder();
//Create Thumbnail
FileUpload1.SaveAs(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image img1 = System.Drawing.Image.FromFile(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image bmp2 = img1.GetThumbnailImage(100, 100, null, IntPtr.Zero);
bmp2.Save(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\thumbnail\L\" + FileUpload1.FileName);
//Load the images selected by user
for (int i = 0; i <= ItemList.Count - 1; i++)
{
Control MyUserControl;
// Load user control dynamically
MyUserControl = LoadControl("MyControl.ascx");
MyUserControl.ID = "MyUserControl" + cnt++;
// Assign URL
Image MyImage = (Image)MyUserControl.FindControl("Image1");
// MyImage.ID = "Image" + cnt;
MyImage.ImageUrl = "~/SaveImage/thumbnail/L/" + ItemList[i].ToString();
// Add control to panel.
p.Controls.Add(MyUserControl);
Panel2.Controls.Add(p);
</code>
Problem :
1> All images come on new line i want them next to each other.
2> How to detect which radio button is clicked as i have more than one images, and all have radio buttons.
3> How to capture click of radio button from aspx page?
4> If there is some other way to achieve this let me know.
Searched on google but could not find a solution for this. :(
Thanks in advance.
[Code After Changes]
in ascx file i have added following code
public event EventHandler rd_ClickDemo;
protected void deleteimage_CheckedChanged(object sender, EventArgs e)
{
rd_ClickDemo(sender, e);
}
protected void setascover_CheckedChanged(object sender, EventArgs e)
{
rd_ClickDemo(sender, e);
}
In aspx file on click of a button i am doing the following.
protected void btnAddURL_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
// Add file name to array list
ItemList.Add(FileUpload1.FileName);
//Add The URL in a text box.
txtAddURL.Text = txtAddURL.Text + System.Environment.NewLine + System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
//Image1.ImageUrl = System.IO.Path.GetFullPath(FileUpload1.PostedFile.FileName);
//this.Button1_Click(this, e);
showImage();
}
}
public void showImage()
{
PlaceHolder p = new PlaceHolder();
// Create a Thumbnail Image.
FileUpload1.SaveAs(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image img1 = System.Drawing.Image.FromFile(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\" + FileUpload1.FileName);
System.Drawing.Image bmp2 = img1.GetThumbnailImage(100, 100, null, IntPtr.Zero);
bmp2.Save(#"D:\ASP\Project_Dec_16\RealEstate\SaveImage\thumbnail\L\" + FileUpload1.FileName);
//Load all images from array list.
for (int i = 0; i <= ItemList.Count - 1; i++)
{
// Load user control dynamically
MyUserControl = LoadControl("MyControl.ascx");
MyUserControl.ID = "MyUserControl" + cnt++;
// Find Radio Button
RadioButton rdb1 = (RadioButton)MyUserControl.FindControl("deleteimage");
RadioButton rdb2 = (RadioButton)MyUserControl.FindControl("setascover");
//Attach Group Name.
rdb1.GroupName = "G1" + cnt.ToString();
rdb1.ID = "Rb_ID_D" + cnt.ToString();
rdb1.AutoPostBack = true;
rdb1.CheckedChanged +=new EventHandler(rdb1_CheckedChanged);
//Attach Group Name.
rdb2.GroupName = "G1"+ cnt.ToString();
rdb2.ID = "Rb_ID" + cnt.ToString();
rdb2.AutoPostBack = true;
rdb2.CheckedChanged += new EventHandler(rdb1_CheckedChanged);
//Image MyImage = (Image)MyUserControl.FindControl("Image1");
// MyImage.ID = "Image" + cnt;
//Attach URL to Image.
Image MyImage = (Image)MyUserControl.FindControl("Image1");
MyImage.ImageUrl = "~/SaveImage/thumbnail/L/" + ItemList[i].ToString();
p.Controls.Add(MyUserControl);
Panel2.Controls.Add(p);
}
}
Still i am not able to trigger the radiobutton_CheckedChanged event.
Please Help.
Ok so here is your solution for first problem:
1> All images come on new line i want them next to each other.
Ans: You can do so in CSS of your custom control's div block, just set the float to left like this
style="display:block;float:right;"
2> How to detect which radio button is clicked as i have more than one images, and all have radio buttons.
Ans: You can get the control which host your RadioButton so u can use NamingContainer property of the Radio button to get the hosting control, which in your case must be you custom control.
3> How to capture click of radio button from aspx page?
Ans: Do the following in your code:
first when you loop to add You custom control to your Panel2 attach a groupname and a event handler to the RadioButton. (Assuming you already have your radio buttons in your custom control) and then handle the CheckedChanged Event (i am using anonymous delegate for handling event)
RadioButton rdb1 = (RadioButton)MyUserControl.FindControl("deleteimage");
RadioButton rdb2 = (RadioButton)MyUserControl.FindControl("setascover");
rd1.GrouprdoSelect2.GroupName = "radiobutton" + i.ToString() ;
rd1.ID = "radiobutton" + i.ToString() + i.ToString() + Convert.ToString(1);
rd1.AutoPostBack = true;
rd1.CheckedChanged += (thesender, ev) => {
RadioButton rb = (RadioButton) thesender;
MyUserControl mcl = rb.NamingContainer as MyUserControl;
//Perform your task based on the fact of mcl.ID
}
rd2.GrouprdoSelect2.GroupName = "radiobutton" + i.ToString() ;
rd2.ID = "radiobutton" + i.ToString() + i.ToString() + Convert.ToString(2);
rd2.AutoPostBack = true;
rd2.CheckedChanged += (thesender, ev) => {
RadioButton rb = (RadioButton) thesender;
MyUserControl mcl = rb.NamingContainer as MyUserControl;
//Perform your task based on the fact of mcl.ID
}

C# Web browser control is not updating correctly

I'm currently working on an app that technically interacts with an html page that uses dynamic content.
My problem is when I try to append data to the WBC the content isn't updating correctly.
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
.... code removed ....
private void button2_Click(object sender, EventArgs e)
{
if (textBox1.Text != null)
{
HtmlDocument doc = webBrowser1.Document;
HtmlElement row = doc.CreateElement("tr");
HtmlElement cell1 = doc.CreateElement("td");
HtmlElement cell2 = doc.CreateElement("td");
cell1.InnerHtml = "[X] " + textBox1.Text;
cell2.SetAttribute("class", "solved_2");
cell2.InnerHtml = "Unsolved";
row.AppendChild(cell1);
row.AppendChild(cell2);
doc.GetElementsByTagName("table")[0].AppendChild(row);
//doc.Write(doc.GetElementsByTagName("HTML")[0].OuterHtml);
webBrowser1.Document.Body.InnerHtml = doc.Body.InnerHtml;
}
}
}
}
What currently happens is, I click "add" it should add the html to the page and update and the javascript and what not should still load.
What happens is it adds the content, but the javascript doesn't work after I attempt to reload the content. The CSS stays in tact though, and the javascript isn't working after that point.
JS Source:
var showalert = true;
var file = "file:///C:/Users/Removed/Documents/Visual Studio 2010/Projects/CheckList/CheckList/bin/Release/";
initiate_instance();
function initiate_instance() {
//insert
$.get(file + "saved.html", function(data) {
//$("table#items").append("<tr><th width='70%'>Issue</th><th width='30%' class='right'>Solved</th></tr>");
$("table#items").html($("table#items").html() + data);
});
//change [X] into a link
$("table#items tr td").each(function() {
$(this).html($(this).html().replace("[X]", "<a onclick='return remove(this)' href='#'>[X]</a>"));
});
//change the css
$("table#items tr:odd").attr("class", "odd");
$("table#items tr td:eq(0)").attr("width", "70%");
$("table#items tr td:eq(1)").attr("width", "30%");
$("td.solved, td.solved_2").click(function() {
if($(this).attr("class") == "solved") {
$(this).attr("class", "solved_2");
$(this).text("Unsolved");
} else {
$(this).attr("class", "solved");
$(this).text("Solved");
}
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
});
}
//delete rows
function remove(obj) {
if(showalert == true) {
alert("Remember, for these changes to keep effect please save before closing the program.");
showalert = false;
}
$(obj).parent().parent().remove();
return false;
}
TL;DR: Have you tried setting "AllowNavigation" to true?
If you need to prevent navigation, but still need to update the page, a method I've found that works requires:
Initializing the WebBrowser control's DocumentText property with empty HTML to initialize the internal objects (i.e.: Document, DomDocument, Document.Body, etc)
Allowing navigation and the revoking upon page completion (if needed)
Code:
namespace CheckList
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// Initialize all the document objects
webBrowser1.DocumentText = #"<html></html>";
// Add the Document Completed event handler to turn off navigation
webBrowser1.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(webBrowser1_DocumentCompleted);
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// Load default information via LoadHtml(string html);
LoadHtml(#"<html><head></head><body>Text!<script type='text/javascript' language='javascript'>alert('Aha!');</script></body></html>");
}
private void LoadHtml(string html)
{
webBrowser1.AllowNavigation = true;
// This will trigger a Document Completed event
webBrowser1.DocumentText = html;
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
// Prevent further navigation
webBrowser1.AllowNavigation = false;
// Clean-up the handler if no longer needed
}
private void button2_Click(object sender, EventArgs e)
{
// Do your document building
LoadHtml(doc.Body.Parent.OuterHtml);
}
}
}
I've found doing it this way:
Prevents users from navigating until allowed
Allows execution of JavaScript (immediately before OnDocumentCompleted fires)

Programmatically create asp:Button and attach event in SharePoint

I'm trying to create ASP.NET buttons programmatically inside an update panel in my SharePoint instance, but because of the page life cycle, I can not attach server side events on buttons.
Here is the code:
TableCell tcellbutton = new TableCell();
b.Click += new EventHandler(b_Click);
b.CausesValidation = true;
tcellbutton.Controls.Add(b);
tr.Cells.Add(tcellbutton);
table.Rows.Add(tr);
panel1.Controls.Add(table);
void b_Click(object sender, EventArgs e)
{
string studentnumber = (sender as Button).ID.ToString().Substring(3, (sender as Button).ID.ToString().Length - 3);
TextBox t = panel1.FindControl("txt" + studentNumber) as TextBox;
}
Is there another way to create and attach buttons in Sharepoint?
Ok here is how I solved it, Thanks for all replies, I was looking for a way to attach an event to a button that is created dynamically during runtime (after initialization). Hope It works for others as well.
<script type="text/javascript">
function ButtonClick(buttonId) {
alert("Button " + buttonId + " clicked from javascript");
}
</script>
protected void Button_Click(object sender, EventArgs e)
{
ClientScript.RegisterClientScriptBlock(this.GetType(), ((Button)sender).ID, "<script>alert('Button_Click');</script>");
Response.Write(DateTime.Now.ToString() + ": " + ((Button)sender).ID + " was clicked");
}
private Button GetButton(string id, string name)
{
Button b = new Button();
b.Text = name;
b.ID = id;
b.Click += new EventHandler(Button_Click);
b.OnClientClick = "ButtonClick('" + b.ClientID + "')";
return b;
}
You should add your code in PreInit event, code below work good:
protected override void OnPreInit(EventArgs e)
{
base.OnPreInit(e);
Button bb = new Button();
bb.Click += new EventHandler(bb_Click);
bb.CausesValidation = true;
bb.ID = "button1";
Panel1.Controls.Add(bb);
}
private void bb_Click(object sender, EventArgs e)
{
Response.Write("any thing here");
}
You are creating dynamic controls. Your code should execute in each PageLoad event.
Remove IsPostBack for the part of code where you are creating the buttons is my advice.
If you don't do this, you will create the controls, but each time when PageLoad event occurs, your control will be deleted and the application will not follow your events. With other words you should always recreate the controls.

How to show address bar in WebBrowser control

How to show address bar in WebBrowser control in a Windows Form?
I could be mistaken but I don't believe the WebBrowserControl includes the address bar, toolbar, etc. I believe you'll have to create your own address bar. You could use the Navigated or Navigating events to determine when the URL is changing and update the text box.
private void button1_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBox1.Text))
{
webBrowser1.Navigate(textBox1.Text);
}
}
private void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
if (textBox1.Text != e.Url.ToString())
{
textBox1.Text = e.Url.ToString();
}
}
Edit: My form has a TextBox named textBox1, a Button named button1 and a WebBrowserControl named webBrowser1
You could make a textbox and then fill it with the site property i think
Drag and drop a text box into your form.
Use the URL.ToString method to set the textbox .text value to that url string:
Dim strURL As String
strURL = ""
If Me.TextBox1.Text.Length = 0 Then
Me.TextBox1.Focus()
Me.TextBox1.BackColor = Color.Red
Else
If InStr(Me.TextBox1.Text, "http://") = 0 Then
strURL = "http://" & Me.TextBox1.Text.ToString()
Else
strURL = Me.TextBox1.Text.ToString()
End If
Me.WebBrowser1.Navigate(New System.Uri(strURL))
Me.TextBox1.Text = Me.WebBrowser1.Url.ToString()
End If
Here's C#:
string strURL = null;
strURL = "";
if (this.TextBox1.Text.Length == 0) {
this.TextBox1.Focus();
this.TextBox1.BackColor = Color.Red;
}
else {
if (Strings.InStr(this.TextBox1.Text, "http://") == 0) {
strURL = "http://" + this.TextBox1.Text.ToString();
}
else {
strURL = this.TextBox1.Text.ToString();
}
this.WebBrowser1.Navigate(new System.Uri(strURL));
this.TextBox1.Text = this.WebBrowser1.Url.ToString();
}

Categories