Solved

How to load execCommand inside c#.net! SOS 125 points for u!

Posted on 2003-11-05
18
1,317 Views
Last Modified: 2007-12-19
Hello everyone:

I create a new web application project in VisualC#.net. I put some html tag on it, like 'div'... I am trying to load execCommand function by using C#. I am not writing code in html file. Is this possible?

roughly idea like:
...
using mshtml; (if I am right!)
...

mshtml.HTMLDocument doc;
doc = thispage.getDocument(); // I don't know command, something like this.
// and then
doc.execCommand(a1,a2,a3);

Thank you so much! :)
0
Comment
Question by:visualhaha
  • 9
  • 6
18 Comments
 
LVL 6

Expert Comment

by:purpleblob
Comment Utility
Sorry, can I clear this up are you trying to put HTML directly into the document, execCommand isn't required for this if this is what you want to achieve.

To put HTML into a document simply do the following:

mshtml.IHTMLDocument2 html2;
html2 = (mshtml.IHTMLDocument2)browser.Document;
html2.writeln(new object[]{htmldoc});
html2.close();

where htmldoc is your HTML code i.e. string htmldoc = "<html><head></head><body></body></html>";

And yes you could remove the mshtml. parts in the source if you place using mshtml; in your code

If I'm wrong in what you're after then can you please give me a little more info.

0
 
LVL 69

Expert Comment

by:Callandor
Comment Utility
I smell a rat here... http://www.experts-exchange.com/Programming/Q_20788384.html looks just like this one.
0
 

Author Comment

by:visualhaha
Comment Utility
Hi Callandor:
Thank you for reply. I am beginner in C#.net.
XmlTextWriter&StreamWriter class may work, but I don't know how to get handle of "IE" which I am just opened.  Thanks again!
0
 

Author Comment

by:visualhaha
Comment Utility
Hi Callandor: totally 250 points waitting for you!
0
 

Author Comment

by:visualhaha
Comment Utility
Hi purpleblob:
Sorry I didn't describe my question clearly. :)
1. I create a new web application in MSVC#.net.
2. Automatically I get code like following:
-----------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Reflection;
using mshtml;
using SHDocVw;
using EnvDTE;

namespace WebApplication13
{
      /// <summary>
      /// Summary description for WebForm1.
      /// </summary>
      public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.HtmlControls.HtmlGenericControl DIV1;
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.Button Button2;
            protected System.Web.UI.WebControls.TextBox TextBox1;
      
            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
                  DIV1.InnerHtml = "hello";

            }

            #region Web Form Designer generated code
            override protected void OnInit(EventArgs e)
            {
                  //
                  // CODEGEN: This call is required by the ASP.NET Web Form Designer.
                  //
                  InitializeComponent();
                  base.OnInit(e);
            }
            
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {    
                  this.Button1.Click += new System.EventHandler(this.Button1_Click);
                  this.Button2.Click += new System.EventHandler(this.Button2_Click);
                  this.Load += new System.EventHandler(this.Page_Load);

            }
            #endregion

            private void Button1_Click(object sender, System.EventArgs e)
            {
                  TextBox1.Text = DIV1.InnerHtml;
            }

            private void Button2_Click(object sender, System.EventArgs e)
            {
                  mshtml.IHTMLDocument2 html2;
                  html2 = (mshtml.IHTMLDocument2)browser.Document;
                  html2.writeln(new object[]{htmldoc});
                  html2.close();
            }
      }
}

-----------------------------------------------------
3. I manual add a 'div' control on it name "DIV1", and a button name "Button2".

4. My purpose is when I click "Button2", I will 'bold' "DIV1" by loading "document.execCommand". But I don't know how to do it because I don't know how to get handle of current "IE".

5. Just in your reply:
    mshtml.IHTMLDocument2 html2;
    html2 = (mshtml.IHTMLDocument2)browser.Document; // idea is right!
    html2.writeln(new object[]{htmldoc});
    html2.close();
    -------------
    Where ‘browser’ come from? If I compile this, it gives me error messenger:
c:\inetpub\wwwroot\WebApplication13\WebForm1.aspx.cs(98): The type or namespace name 'browser' could not be found (are you missing a using directive or an assembly reference?)

Waitting your reply! Thank you!
0
 
LVL 6

Expert Comment

by:purpleblob
Comment Utility
Well I assumed, since you'd mentioned something called thispage.getDocument that you'd already an understanding of adding the web browser control etc.

Have you added a browser control to your application as a reference ?

If not, you need to add reference shdocw.dll (or select Microsoft web browserfrom the COM tab). You'll also need to add reference to Microsoft HTML Object Library (mshtml.tlb). Then declare a variable

private AxSHDocVw.AxWebBrowser browser;

However this is if you intended to embed IE within your application. If on the other hand you're trying to interact with an open copy of IE, then this is a different issue altogether.

Could you clarify - do you want to embed an HTML document within an application or are you wishing to try and interact with an existing (open) copy of IE ?
0
 

Author Comment

by:visualhaha
Comment Utility
Hi purpleblob:
I am trying interact with an existing browser!
Thank you!
0
 

Author Comment

by:visualhaha
Comment Utility
you can delete another account. I lost password of it!
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 6

Expert Comment

by:purpleblob
Comment Utility
Okay, then the following example shows how to get an existing IE browser object.

SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)Marshal.GetActiveObject("InternetExplorer.Application");

If you want to write a new page to the browser then my previous example code will do this. i.e.

mshtml.IHTMLDocument2 html2;
html2 = (mshtml.IHTMLDocument2)browser.Document;
html2.writeln(new object[]{htmldoc});
html2.close();

Or were you wanting to edit an existing HTML document ?
0
 

Author Comment

by:visualhaha
Comment Utility
Hi purpleblob:

Thank you so much, I think you are very close, but before I give you points, I still have a question to ask you.

Please have a look my code. I create a web application in C#.net, that web form called “WebForm1.aspx”, and then I put a “DIV1” and a button name “Button2” on it. My purpose is when I click button I can load function like “DIV1.document.execCommand(cmd,bShow,opt);” .

When I try your code, compile ok, but it give me an error message:

by the way, I don't think your way is the best solution, (maybe I am wrong @_@) because there is a pointer "this" pointing to current page object. Please help!

------------------------------------------------------------------------
Server Error in '/WebApplication13' Application.
 
Operation unavailable
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Runtime.InteropServices.COMException: Operation unavailable

Source Error:

Line 92:                   //dte = DTE.Properties("Environment", "WebBrowser");
Line 93:                   //string fcdoc = dte.ActiveDocument.Name;
Line 94:                   dte = (EnvDTE.DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.7.1");
Line 95:
Line 96:                   //this.

Source File: c:\inetpub\wwwroot\webapplication13\webform1.aspx.cs    Line: 94

Stack Trace:

[COMException (0x800401e3): Operation unavailable]
   System.Runtime.InteropServices.Marshal.GetActiveObject(Guid& rclsid, UInt32 reserved, Object& ppunk) +0
   System.Runtime.InteropServices.Marshal.GetActiveObject(String progID) +77
   WebApplication13.WebForm1.Button2_Click(Object sender, EventArgs e) in c:\inetpub\wwwroot\webapplication13\webform1.aspx.cs:94
   System.Web.UI.WebControls.Button.OnClick(EventArgs e)
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   System.Web.UI.Page.ProcessRequestMain()
-------------------------------------------------------------------------
Here is code for “WebForm1.aspx.cs”
-------------------------------------------------------------------------
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

using System.Reflection;
using mshtml;
using SHDocVw;
using EnvDTE;
using System.Runtime.InteropServices;
using System.Threading;


namespace WebApplication13
{
      /// <summary>
      /// Summary description for WebForm1.
      /// </summary>
      public class WebForm1 : System.Web.UI.Page
      {
            protected System.Web.UI.HtmlControls.HtmlGenericControl DIV1;
            protected System.Web.UI.WebControls.Button Button1;
            protected System.Web.UI.WebControls.Button Button2;
            protected System.Web.UI.WebControls.TextBox TextBox1;
            
            //private SHDocVw.WebBrowser browser;

            private void Page_Load(object sender, System.EventArgs e)
            {
                  // Put user code to initialize the page here
                  DIV1.InnerHtml = "hello";      // 'DIV1' here !
            }
            ... ...
            private void Button2_Click(object sender, System.EventArgs e)
            {
                  SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)Marshal.GetActiveObject("Word.Application");
                  browser.doument.execCommand("DIV1","","");      // load execCommand
            }
      }
}
--------------------------------------------------
Thanks Again!

0
 
LVL 6

Expert Comment

by:purpleblob
Comment Utility
I'm sorry but this code you've presented cannot possibly work - I don't know whether this is a typo within your code or what. Firstly there's the last line of code

browser.doument.execCommand - this should be document.execCommand

Secondly you are trying to create a Word.Application using GetActiveObject but then trying to cast this to a SHDocVw.IWebBrowser2 - I am not aware that Word supports such an interface.

With regards my code snippet not being the best solution - this is probably the case (see below).

Actually the solution I've described is not suitable for what you are trying to do  - if you are talking about the button executing the browsers execCommand on the client machine then this will not work as you are running this code on the server side, you need to use JavaScript on the client side to handle this - whilst you specified that the app. was a web application you didn't point out this was using ASP.NET - this brings in the issues of what can execute on the client or on the server and is a totally different ball game.

So would you mind confirming - is the idea that your application is displayed on a browser on the client's machine - whenthe user presses the button it should execCommand on the client machine ?
0
 

Author Comment

by:visualhaha
Comment Utility
1. Sorry, I made big mistake, this should be
SHDocVw.IWebBrowser2 browser = (SHDocVw.IWebBrowser2)Marshal.GetActiveObject("InternetExplorer.Application"); //Sorry.

2. Yes! I display a browser on the client's machine, whenthe user presses the button it should execCommand on the client machine! Yes! This is my idea.
0
 
LVL 6

Accepted Solution

by:
purpleblob earned 125 total points
Comment Utility
Then your design is not going to work I'm afraid.

You are using a button that will cause an event to occur on the server - the current code will then try to get a browser object on the server and then attempt to call execCommand on this object - all on the server. So imagine you're working on your server when this happens you'll see the browser window do something or other on the server but the client will not see anything at their end.

If I understand what you want to achieve then you need to alter your design to use a non-server side button, catch the onclick event in the HTML and use JavaScript to interact with the browser object.

Something like

<INPUT style="Z-INDEX: 102; LEFT: 142px; WIDTH: 184px; POSITION: absolute; TOP: 128px; HEIGHT: 49px" onclick="document.execCommand('SaveAs');" type="button" value="Button">

Now the example here will operate solely on the client machine and will cause the SaveAs dialog to appear

0
 

Author Comment

by:visualhaha
Comment Utility
ok! :( thank you purpleblob! I will wait another 3 days.
0
 

Author Comment

by:visualhaha
Comment Utility
This question still opening, if someone get good idea.
0
 
LVL 6

Expert Comment

by:purpleblob
Comment Utility
I wonder if you'd like to explain why you only gave me a C grade.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

In order to hide the "ugly" records selectors (triangles) in the rowheaders, here are some suggestions. Microsoft doesn't have a direct method/property to do it. You can only hide the rowheader column. First solution, the easy way The first sol…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now