Windows form show html

Show HTML Content on a Windows Form

CodeProject offers a range of references for HTML rendering. If you need managed HTML rendering, check out Professional HTML Renderer. For dynamic HTML rendering, take a look at Show Dynamic HTML in WinForm Applications. There are three solutions provided, each with different steps to follow. The first solution requires you to write specific code in form1 and form2. The second solution suggests trying a certain approach. The third solution suggests another option, which involves gathering all necessary information about formatting numbers and dates in .NET from form1.

Display HTML on a winform

One possibility is to use the web browser control, which allows for direct injection of all HTML code.

webBrowser1.DocumentText = "hello "; 

Utilize the WebBrowser control that is integrated within the system.

References at CodeProject:

To access a professional HTML renderer, refer to the Managed HTML Rendering.

To view Dynamic HTML in WinForm Applications, refer to the section on Showcasing Dynamic HTML.

webBrowser1.Document.Write(yourHtmlText); 

How do I implement a TextBox that displays «Type here»?, Displaying «Type here to » until the user enters text into a TextBox is a well-known usability feature nowadays.How would one implement this feature in C#? My idea is to override OnTextChanged, but the logic to handle the changes of text from and to «Type here» is a bit tricky. Displaying «Type here» on …

Читайте также:  Indianvisaonline gov in visa tvoa html

How to Display value of textbox in label in another form?

private void button1_Click(object sender, EventArgs e)
 // In Form1.cs. private Form2 otherForm = new Form2(); private void GetOtherFormTextBox() < textBox1.Text = otherForm.label1.Text; >private void button1_Click(object sender, EventArgs e) GetOtherFormTextBox(); > 
private void button1_Click(object sender, EventArgs e)
private string labelText; public string LabelText < get < return labelText; >set < labelText = value; >> private void Form2_Load(object sender, EventArgs e)

Winforms — Set default value by textbox in C#, You can enter strings there and give them a name. Create a string and call it UserEmail (The value you enter now will be the default value for new installations). In the Form where the value should be shown create a method that is called when the Form is loaded (perhaps called from Form_Load):

How to set the value of a textbox textmode=date ASP.NET C#

The issue at hand pertains to Html5, rather than asp.net. To ensure compliance with the W3C standard, it is recommended to utilize the format indicated by yyyy-MM-dd when working with type=»date» .

In non-type=date supporting browsers, the display will be shown as 2014-03-30 . However, for browsers that support it, the display will be based on the regional settings of the client’s operating system.

You do not have control over the format of the code as it could be either 2014-03-30 , 30.March.2014 , or Mar-30-2014 . The user determines the format.

As far as I know, the recently added textbox in .Net, utilizing textmode=date , solely accepts the YYYY-MM-DD structure.

txtDataDespesa.Text = d.DataDespesa.ToString("yyyy-MM-dd") 

To obtain the abbreviated date string, a standard text box must be utilized.

dt_calculate_to_date.Text = DateTime.Today.ToString("yyyy-MM-dd"); 

Default value for TextBoxFor in ASP.NET MVC, In ASP.NET MVC, I wrote below code to give the textbox a initial value: @Html.TextBoxFor(p => p.WEIGHT, new < tabindex = "140", @class = "mustInputText no

C# textbox decimal formatting

Whenever feasible, I strongly suggest utilizing the pre-existing format strings that come with the system, for instance, N2 .

string s = number.ToString("N2"); 

Quick Reference Cheat Sheet When you’re unsure, refer to John Sheehan’s .NET Format String. It contains all the necessary details regarding formatting numbers and dates in .NET.

Typically, when using DevExpress controls, it is necessary to specify the type of content being formatted, such as a number or date.

calcEdit.Properties.DisplayFormat.FormatType = FormatType.Numeric; calcEdit.Properties.DisplayFormat.FormatString = "N2"; 

Failure to specify the format type will result in the format string not being utilized.

Instead of using TextEdit, it is recommended to indicate a Mask.

textEdit.Properties.Mask.MaskType = MaskType.Numeric; textEdit.Properties.Mask.EditMask = "N2"; 

To illustrate, consider a variable called «amount» and format it in the following manner:

The amount will be displayed with precision up to two decimal places.

Attempt #,##0.00 without utilizing the «#» at the end.

C# textbox decimal formatting, I want my text boxes which are binded to money (SqlServer) entity fields, to show just two decimal places instead of four places. I use DevExpress textEdit and CalcEdit boxes with the following display and edit format : «#,##0.00#;(#,##0.00#)»; But I always get four decimal places (zeros).. I use the same format string in …

Источник

How to: Access the HTML Source in the Managed HTML Document Object Model

The DocumentStream and DocumentText properties on the WebBrowser control return the HTML of the current document as it existed when it was first displayed. However, if you modify the page using method and property calls such as AppendChild and InnerHtml, these changes will not appear when you call DocumentStream and DocumentText. To obtain the most up-to-date HTML source for the DOM, you must call the OuterHtml property on the HTML element.

The following procedure shows how to retrieve the dynamic source and display it in a separate shortcut menu.

Retrieving the dynamic source with the OuterHtml property

  1. Create a new Windows Forms application. Start with a single Form, and call it Form1 .
  2. Host the WebBrowser control in your Windows Forms application, and name it WebBrowser1 . For more information, see How to: Add Web Browser Capabilities to a Windows Forms Application.
  3. Create a second Form in your application called CodeForm .
  4. Add a RichTextBox control to CodeForm and set its Dock property to Fill .
  5. Create a public property on CodeForm called Code .
public string Code < get < if (richTextBox1.Text != null) < return (richTextBox1.Text); >else < return (""); >> set < richTextBox1.Text = value; >> 
Public Property Code() As String Get If (RichTextBox1.Text IsNot Nothing) Then Code = RichTextBox1.Text Else Code = "" End If End Get Set(ByVal value As String) RichTextBox1.Text = value End Set End Property 
private void button1_Click(object sender, EventArgs e) < HtmlElement elem; if (webBrowser1.Document != null) < CodeForm cf = new CodeForm(); HtmlElementCollection elems = webBrowser1.Document.GetElementsByTagName("HTML"); if (elems.Count == 1) < elem = elems[0]; cf.Code = elem.OuterHtml; cf.Show(); >> > 
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim elem As HtmlElement If (WebBrowser1.Document IsNot Nothing) Then Dim cf As New CodeForm() Dim elems As HtmlElementCollection = WebBrowser1.Document.GetElementsByTagName("HTML") If (elems.Count = 1) Then elem = elems(0) cf.Code = elem.OuterHtml cf.Show() End If End If End Sub 

Robust Programming

Always test the value of Document before attempting to retrieve it. If the current page is not finished loading, Document or one or more of its child objects may not be initialized.

See also

Источник

Используем HTML и WebBrowser control в качестве UI для обычных windows-приложений на C#

Как известно, контрол WebBrowser это просто обертка над ActiveX компонентом Internet Explorer. Следовательно он предоставляет доступ к полноценному layout-движку со всеми современными плюшками. А раз так, то попробуем (сам не знаю правда зачем) на его основе сделать пользовательский интерфейс для обычного windows-приложения.

Можно, конечно, было бы запустить в этом же процессе мини веб-сервер (на HttpListener например) и ловить запросы через него, но это слишком просто, скучно и неспортивно. Попробуем обойтись без сетевых компонентов, just for fun.

Итак, задача проста — необходимо перехватывать отправку HTML-форм и выводить новый HTML-документ, сгенерированный логикой приложения в зависимости от POST-параметров.

Прежде всего нам понадобится Windows Forms Application с одной единственной формой на которой будет один единственный контрол — WebBrowser занимающий все пространство.

Для примера рисуем пару простых страниц интерфейса (с минимальным содержимым для краткости, а так скрипты и стили добавлять по вкусу).

Примечание: X-UA-Compatible необходим для корректного отображения некоторых стилей, в данном примере они не используются, но проблема есть. Не буду вдаваться в детали, но без этого компонент рисует страницы в режиме совместимости с чем то очень старым, со всеми вытекающими последствиями.

WebBrowser предоставляет несколько событий, среди которых есть например Navigating, которое срабатывает перед тем как отправить форму или перейти по ссылке.
Практически то что нужно, но это событие не предоставляет никакой информации о post-параметрах. GET-параметры использовать не получится поскольку у наших HTML-форм атрибут action отсутствует, что приведет к тому что в качестве URL всегда будет about:blank и никакой информации о GET параметрах не будет.
Для получения более подробной информации о запросе надо подписаться на событие BeforeNavigate2 (подробнее тут) у внутреннего COM-объекта браузера, благо он доступен через свойство ActiveXInstance.
Сделать это проще всего через dynamic, чтобы не возиться с объявлением COM-интерфейсов:
Объявляем делегат:

private delegate void BeforeNavigate2(object pDisp, string url, int Flags, string TargetFrameName, byte[] PostData, string Headers, ref bool Cancel); 

Затем подписываемся на событие (в конструкторе формы у WebBrowser свойство ActiveXInstance будет null, потому это лучше сделать после того как окно загрузится, т.е. в OnLoad например):

((dynamic)webBrowser.ActiveXInstance).BeforeNavigate2 += new BeforeNavigate2(OnBeforeNavigate2); 

Итак, в PostData лежат post-параметры в виде строки состоящей из пар ключ=значение объединенных через &. Разделяем их и укладываем в словарь:

var parameters = (PostData == null ? string.Empty : Encoding.UTF8.GetString(PostData)) .Split('&') .Select(x => x.Split('=')) .Where(x => x.Length == 2) .ToDictionary(x => WebUtility.UrlDecode(x[0]), x => WebUtility.UrlDecode(x[1])); 

Кроме того, в этом обработчике лучше отменить действие через параметр Cancel, чтобы лишний раз не попадать на about:blank.

Имея параметры генерируем текст новой страницы. Сюда теоретически прикручивается какой-н менеджер обработчиков, выбирающий необходимый обработчик в зависимости от параметров, которые по каким-н шаблонам будут собирать страницы из кусочков, но для краткости пока для примера просто по кнопке page1 откроем первую страницу, по кнопке page2 — вторую (имена кнопок в разметке указывать обязательно, иначе из post-параметров не определить какую именно кнопку нажали), а также заменим все строки в круглых скобках на значения параметров с такими именами:

 private static string Handler(IReadOnlyDictionary parameters) < // do some useful stuff here var newPage = "Not found"; if (parameters.ContainsKey(nameof(page1))) newPage = page1; if (parameters.ContainsKey(nameof(page2))) newPage = page2; parameters.ToList().ForEach(x =>newPage = newPage.Replace("", x.Value)); return newPage; > 

Полученную строку с HTML-текстом записываем в свойство DocumentText WebBrowser-а.
И тут же получим бесконечный цикл перезагрузки страницы, поскольку установка этого свойства спровоцирует новый вызов OnBeforeNavigate2.
Временно отписаться от этого события не получится, поскольку вызывается оно откуда то из цикла обработки сообщений уже после того как установка DocumentText возвращает управление.
Т.о. необходимо всегда игнорировать каждый второй вызов обработчика, поскольку первое срабатывание это отправка формы в результате действий пользователя, которое обрабатывать нужно, а второе — отображение результата которое обрабатывать не нужно. Для простоты будем в начале обработчика OnBeforeNavigate2 переключать bool переменную.

ignore = !ignore; if (ignore) return; 

Это все что необходимо для минимального приложения. Но работать таким образом будет не все — за рамками осталось например получение данных о файлах для input type=«file», а также работа с XMLHttpRequest для корректной работы скриптов со всякими там ajax.

using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Windows.Forms; namespace TestHtmlUI < internal sealed class MainForm : Form < private const string page1 = @"    
"; private const string page2 = @"
"; private delegate void BeforeNavigate2(object pDisp, string url, int Flags, string TargetFrameName, byte[] PostData, string Headers, ref bool Cancel); private readonly WebBrowser webBrowser = new WebBrowser < Dock = DockStyle.Fill >; private bool ignore = true; private MainForm() < StartPosition = FormStartPosition.CenterScreen; Controls.Add(webBrowser); Load += (sender, e) =>((dynamic)webBrowser.ActiveXInstance).BeforeNavigate2 += new BeforeNavigate2(OnBeforeNavigate2); webBrowser.DocumentText = Handler(new Dictionary < < nameof(page1), string.Empty >>); > private void OnBeforeNavigate2(object pDisp, string url, int Flags, string TargetFrameName, byte[] PostData, string Headers, ref bool Cancel) < ignore = !ignore; if (ignore) return; Cancel = true; var parameters = (PostData == null ? string.Empty : Encoding.UTF8.GetString(PostData)) .Split('&') .Select(x =>x.Split('=')) .Where(x => x.Length == 2) .ToDictionary(x => WebUtility.UrlDecode(x[0]), x => WebUtility.UrlDecode(x[1])); webBrowser.DocumentText = Handler(parameters); > [STAThread] private static void Main() < Application.EnableVisualStyles(); Application.Run(new MainForm()); >private static string Handler(IReadOnlyDictionary parameters) < var newPage = "Not found"; if (parameters.ContainsKey(nameof(page1))) newPage = page1; if (parameters.ContainsKey(nameof(page2))) newPage = page2; // do dome usefull stuff here parameters.ToList().ForEach(x =>newPage = newPage.Replace("", x.Value)); return newPage; > > >

Источник

Оцените статью