How to open IE with post info in C#?

后端 未结 6 1260
陌清茗
陌清茗 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条回答
  •  萌比男神i
    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);
      }
    }
    

提交回复
热议问题