How to open IE with post info in C#?

后端 未结 6 1251
陌清茗
陌清茗 2020-12-03 12:32

I am developing a small program which as a windows form. On this form, I want to put a link, and when user click the link, a seperate IE browser will be open with post data.

相关标签:
6条回答
  • 2020-12-03 12:44

    Drop a web browser on your form. It should have a default name of "webBrowser1" - you can change that if you like. Set the "Visible" property to "False". Double-click the form title bar to auto generate a load event in the code.

    Call the Navigate method, which has this signature:

    void Navigate(string urlString, string targetFrameName, byte[] postData, string additionalHeaders);
    

    Like this:

    private void Form1_Load(object sender, EventArgs e)
    {
        webBrowser1.Navigate("http://www.google.com/", "_blank", Encoding.Default.GetBytes("THIS IS SOME POST DATA"), "");
    }
    

    You can pass any array of bytes you want in there... Encoding.Default.GetBytes() is just a fast way to pass a string through.

    The trick is to use "_blank" for the target frame.

    0 讨论(0)
  • 2020-12-03 12:44

    You are definitely going to need to use Process.Start (or use a ProcessInfo) to get IE started : like this :

    // open IE to a file on the Desktop as a result of clicking a LinkLabel on a WinForm

    internal static string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
    
    private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
    {
        System.Diagnostics.Process.Start("IExplore.exe", desktopPath + "\\someHTMLFile.htm");
    }
    

    If you scroll down in this page :

    http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start(VS.80).aspx

    (the Process.Start docs for FrameWork 3.0)

    you'll find a user contributed example of using ProcessInfo to control whether more than one of instance of IE is started, and how to pass command line arguments to IE.

    This page :

    http://msdn.microsoft.com/en-us/library/0w4h05yb.aspx

    (the Process.Start docs for FrameWork 3.5)

    shows you a complete example of launching IE, and how to pass url files as arguments.

    I'm not completely clear on what you mean by "Post" in your message (I associate "Post" with ASP.NET), but you could write out an html file in a temporary location with whatever you liked in it, and then pass the address of that file when you launch IE using the techniques documented above. best,

    0 讨论(0)
  • 2020-12-03 12:58

    Actually, you can use process.start with posted query string data:

    System.Diagnostics.Process.Start("IExplore.exe", "http://localhost/file.html?foo=bar&baz=duh");
    
    0 讨论(0)
  • 2020-12-03 12:59

    If you do a ShellExecute with a verb of OPEN on the url then the default web browser will be spawned and open the link. Alternatively, you can invoke Internet Explorer (once again using ShellExecute) with the url appended at the end of the string (so the string that you use for ShellExecute would look like this:

    System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "http://google.com");
    

    You are talking about POST though, you cannot do a POST, the above line does a GET. Depending on how the website is set up you may be able to just append the parameters on the end of the url, like so:

    System.Diagnostics.Process.Start(@"C:\Program Files\Internet Explorer\iexplore.exe", "http://www.google.com/search?q=bing");
    
    0 讨论(0)
  • 2020-12-03 13:00

    You can also use .NET reflection to open a browser

    This example shows you how to set some specific attributes of the InternetExplorer.Application

    For example, I needed to be able to turn off the address bar and set the height and width. IE and other browser security does not allow you to turn off the address bar in the other examples

    Our site is an internal MVC application and works with no issues.

    System.Type oType = System.Type.GetTypeFromProgID("InternetExplorer.Application");
    object IE = System.Activator.CreateInstance(oType);
    
    IE.GetType().InvokeMember("menubar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
    IE.GetType().InvokeMember("toolbar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
    IE.GetType().InvokeMember("statusBar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
    IE.GetType().InvokeMember("addressbar", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 0 });
    IE.GetType().InvokeMember("Visible", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { true });
    IE.GetType().InvokeMember("Height", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 680 });
    IE.GetType().InvokeMember("Width", System.Reflection.BindingFlags.SetProperty, null, IE, new object[] { 1030 });
    IE.GetType().InvokeMember("Navigate", System.Reflection.BindingFlags.InvokeMethod, null, IE, new object[] { "http://yoursite" });
    

    The only drawback here is that this is opening IE specifically. The plus is that it gives you more control over the browser.

    You also have access to the Events, Methods and Properties of the InternetExplorer.Application object.

    https://msdn.microsoft.com/en-us/library/aa752084(v=vs.85).aspx

    I hope that helps someone else as it did me.

    I am working on binding to events and will update this after testing.

    0 讨论(0)
  • 2020-12-03 13:05

    You can just start process by sending URL in Process.Start as parameter. There is a problem while calling StartProcess from WebForms GUI thread because of synchronization context. My solution uses thread pool for this purpose. Advantage of this solution is that an URL is opened in user preferred web browser that can be IE, Firefox etc.

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming",
      "CA1725:ParameterNamesShouldMatchBaseDeclaration", MessageId = "0#"),
     System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
    public void OpenUrl(string urlString)
    {
      try
      {
        ThreadPool.QueueUserWorkItem(delegate { StartProcess(urlString, null); });
      }
      catch (Exception ex)
      {
        log.Error("Exception during opening Url (thread staring): ", ex);
        //do nothing
      }
    }
    
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")]
    public void StartProcess(string processName, string arguments)
    {
      try
      {
        Process process = new Process();
        process.StartInfo.FileName = processName;
        if (!string.IsNullOrEmpty(arguments))
        {
          process.StartInfo.Arguments = arguments;
        }
        process.StartInfo.CreateNoWindow = false;
        process.StartInfo.UseShellExecute = true;
        process.Start();
      }
      catch (Exception ex)
      {
        log.ErrorFormat("Exception in StartProcess: process: [{0}], argument:[{1}], exception:{2}"
                        , processName, arguments, ex);
      }
    }
    
    0 讨论(0)
提交回复
热议问题