Just a quick question are there any issues using a Form to create a Web browser in a WPF application and what are the reasons behind it. Or is it a badly designed application? It is the only one I have seen though I have never seen such a implementation. What could be the WPF equivalent to this?
here is some example code of a WPF Application using a Form.
using System.Windows.Forms;
private static long RunWebBrowserFormAndGetCode()
{
Form webBrowserForm = new Form();
WebBrowser webBrowser = new WebBrowser();
webBrowser.Dock = DockStyle.Fill;
long userID = 0;
var uri = new Uri(#"https://somesite.com/get");
webBrowser.Url = uri;
webBrowserForm.WindowState = FormWindowState.Maximized;
webBrowserForm.Controls.Add(webBrowser);
webBrowserForm.Icon = new System.Drawing.Icon(#"bla.icon");
WebBrowserDocumentCompletedEventHandler documentCompletedHandler = (s, e1) =>
{
try
{
string[] clientID = webBrowser.Url.Segments[2].Split('/');
if (clientID[0].All(char.IsDigit))
{
userID = Int64.Parse(clientID[0]);
webBrowserForm.Close();
}
}
catch (Exception)
{
return;
}
};
Related
I have a simple desktop application which loads .cshtml view in a windows form. I build it and published on my remote machine for a specific folder on drive D. Everything works fine, if only 1 user from this machine runs the instance of this application on a target path. But if any other user try to run the same app, while the copy of that app is already running by another user it sees a blank form instead.
I've already covered the code with some logging and try{} catch{} blocks, but have no interesting info so far. The service which returns the desktop view runs at the same intranet and it returns the result all the time if you just go to URL against the browser.
What could be the problem and how can I find the true cause of its appearance?
I will be grateful for any advice.
Update 1: CoreWebView2InitializationCompleted contains an exception -> The requested resource is in use. (0x800700AA)
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
this.webView = new Microsoft.Web.WebView2.WinForms.WebView2();
((System.ComponentModel.ISupportInitialize)(this.webView)).BeginInit();
this.SuspendLayout();
//
// webView
//
this.webView.AllowExternalDrop = false;
this.webView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.webView.CreationProperties = null;
this.webView.DefaultBackgroundColor = System.Drawing.Color.White;
this.webView.Location = new System.Drawing.Point(10, 10);
this.webView.Name = "webView";
this.webView.Size = new System.Drawing.Size(690, 125);
this.webView.TabIndex = 0;
this.webView.ZoomFactor = 1D;
//
// MainForm
//
this.AccessibleDescription = "MessageBoard Wrapper";
this.AccessibleName = "MessageBoard Wrapper";
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(710, 145);
this.Controls.Add(this.webView);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MinimumSize = new System.Drawing.Size(250, 100);
this.Name = "MainForm";
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
this.Text = "MessageBoard Wrapper";
((System.ComponentModel.ISupportInitialize)(this.webView)).EndInit();
this.ResumeLayout(false);
}
#endregion
private HttpClient GetClient()
{
var result = new HttpClient();
return result;
}
private Microsoft.Web.WebView2.WinForms.WebView2 webView;
private string _baseUrl = "here I have my service url";
public MainForm()
{
InitializeComponent();
FormBorderStyle = FormBorderStyle.None;
DoubleBuffered = true;
SetStyle(ControlStyles.ResizeRedraw, true);
var client = GetClient();
try
{
var targetmUrlForCustomBusinessLogic = "url address here";
var response = client.GetAsync(targetmUrlForCustomBusinessLogic).Result;
if (response.IsSuccessStatusCode)
{
var t = Task.Run(() => response.Content.ReadAsStringAsync()).Result;
//here I have some code too
}
}
catch (Exception ex)
{
var message = ex.Message;
//TODO: add logging here
}
finally
{
client.Dispose();
}
webView.Source = new Uri(_baseUrl);
webView.NavigationCompleted += WebView_NavigationCompleted;
ResizeEnd += (object sender, EventArgs e) => SaveFormSettings();
Move += (object sender, EventArgs e) => SaveFormSettings();
Shown += (object sender, EventArgs e) => LoadFormSettings();
}
I got this application to work in multi user mode by making the following changes.
I removed initialization of webView.Source property
I added a method which is preparing the environment for each user and explicitly trigger the initialization of webView control. (I'm calling this method inside of MainForm
private async Task InitAsync(string path) { var env = await Microsoft.Web.WebView2.Core.CoreWebView2Environment.CreateAsync(userDataFolder: path); await webView.EnsureCoreWebView2Async(env);
}
I set up path param for the user data folder in a next way
path = Path.Combine(Path.GetTempPath(), $"{Environment.UserName}");
I binded navigation path to the target URL in against CoreWebView2InitializationCompleted event handler.
private void webView_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e) { if (webView != null && webView.CoreWebView2 != null) { webView.CoreWebView2.Navigate(_baseUrl); } }
All the steps above solved my issus, which was occuring because each new instance of the app for a new user requred environment folder to deal with webView component. Hope that will save some time for somebody.
I want my application to be work in minimized state.this application is for detecting change in computer language..For example, I change my language from English to Russia application will detect it. But my application not working in minimized state or in taskbar.I have code for show in taskbar.Is there any solution for this problem? I want application to be detect change language(working) while minimized in toolbar
Here I have code for language change detection and to minimized application in toolbar..
private void HandleCurrentLanguage()
{
//CultureInfo.CurrentCulture.ClearCachedData();
//Thread.CurrentThread.CurrentCulture.ClearCachedData();
var newLayout = GetKeyboardLayout(GetWindowThreadProcessId(GetForegroundWindow(), IntPtr.Zero));
if (_currentKeyboardLayout != newLayout)
{
Thread.Sleep(100);
_currentKeyboardLayout = newLayout;
string show = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
// MessageBox.Show(show);
string current_language = InputLanguage.CurrentInputLanguage.Culture.Parent.DisplayName;
string current_layout = InputLanguage.CurrentInputLanguage.LayoutName;
var name = new StringBuilder(_currentKeyboardLayout.ToString());
var keyboardLayoutId = (UInt32)GetKeyboardLayout((UInt32)Thread.CurrentThread.ManagedThreadId);
var languageId = (UInt16)(keyboardLayoutId & 0xFFFF);
var keyboardId = (UInt16)(keyboardLayoutId >> 16);
if (button1.InvokeRequired)
{
button1.Invoke(new MethodInvoker(delegate
{
button1.PerformClick();
}));
}
//CultureInfo.CurrentCulture.ClearCachedData();
//Thread.CurrentThread.CurrentCulture.ClearCachedData();
}
}
// code for minimized application in toolbar
MenuItem exitMenuItem = new MenuItem("Exit", new EventHandler(Exit));
notifyIcon.Icon =SystemTray.Properties.Resources.system_tray;
notifyIcon.Click += new EventHandler(Open);
notifyIcon.ContextMenu = new ContextMenu(new MenuItem[] {
exitMenuItem });
notifyIcon.Visible = true;
I try to create a window on Internet Explorer,just like this:
I wrote this with C++
But I do not know how to design a dialog with MFC,I want to develop this program with c#.
I already know that using BHO can do this work.Here is the core code:
public int SetSite(object site)
{
if (site != null)
{
webBrowser = (SHDocVw.WebBrowser)site;
webBrowser.DocumentComplete += new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
}
else
{
webBrowser.DocumentComplete -= new DWebBrowserEvents2_DocumentCompleteEventHandler(this.OnDocumentComplete);
webBrowser = null;
}
return 0;
}
onDocumentComplete :
SHDocVw.WebBrowser webBrowser;
public void OnDocumentComplete(object pDisp, ref object URL)
{
Form form1 = new Form();
IntPtr p = new IntPtr(webBrowser.HWND);
Control con = Control.FromHandle(p);
con.Controls.Add(form1);
}
But this do not work.Please tell me waht's wrong with my code and how can I do this work.Thank you.
I am developing a chat application using jabber-net opensource library..
my aim is to display a form (chat window ) when a message is coming.
But when I use this code, Form appears in the task bar,,, not perfectly rendered...
seems like this... More over I can see the form only when I mousehover the Icon on taskbar (Hail Windows 7)... Any form are like this...
Click here for Output Image
my code is this...
public jabber.client.JabberClient jabberClient1;
jabberClient1.User = UserName;
jabberClient1.Password = Password;
jabberClient1.Resource = resource;
jabberClient1.AutoRoster = true;
jabberClient1.OnMessage += new MessageHandler(jabberClient1_OnMessage);
private void jabberClient1_OnMessage(object sender, jabber.protocol.client.Message msg)
{
try
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}
you have to use chw.ShowDialog()
or use if invokerequired
private delegate void dlgInvokeRequired();
public void InvokeMethode()
{
if (this.InvokeRequired == true)
{
dlgInvokeRequired d = new dlgInvokeRequired(InvokeMethode);
this.Invoke(d);
} else
{
chatWindow chw = new chatWindow();
chw.Left = 0;
chw.Top = 0;
chw.TopMost = true;
//chw.LoadChat(msg.From.User, msg.From.Bare, "0");
//chw.SetMessage(msg);
chw.Show();
}
}
I have solved it myself...
I have to use
JabberClient1.InvokeControl = FormInstance;
and, the FormInstance should be shown Before the chat window appears....
ie, It can be the contact window (Roster)....
note I am new in Wpf >
I have project that decode qr code by using opencv library throw web cam >
and it running successfully
now I wanna to using this project in new Wpf project >
after adding new wpf project and make reference to WinForms application >
and this my simple code to open WinForm >
public void runnow(){
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new CameraCapture.cameraCapture()); }
by ruining give me this exception >
The type initializer for 'Emgu.CV.CvInvoke' threw an exception.>
what can I do for solve this
C# code
public partial class CameraCapture : Form
{
Capture capture;
bool Capturing;
Bitmap bimap;
private Reader reader;
private Hashtable hint;
libAES libEncryption = new libAES();
string Mykey = "";
public static String dataDecrypted="";
public CameraCapture()
{
InitializeComponent();
}
private void Mains(object sender, EventArgs arg) // Start function main to encode Qr code
{
Image<Bgr, Byte> image = capture.QueryFrame();
if (image != null)
{
bimap = image.ToBitmap();
pictureBox1.Image = bimap;
reader = new QRCodeReader();
hint = new Hashtable(); // Add some elements to the hash table. There are no duplicate keys, but some of the values are duplicates.
hint.Add(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
RGBLuminanceSource source = new RGBLuminanceSource(bimap, bimap.Width, bimap.Height); //This class is used to help decode images from files which arrive as RGB data from* Android bitmaps. It does not support cropping or rotation.
BinaryBitmap img = new BinaryBitmap(new GlobalHistogramBinarizer(source));
Result result = null;
try
{
result = reader.decode(img, hint);
dataDecrypted = libEncryption.Decrypt(result.Text, Mykey);
}
catch
{
dataDecrypted = "";
}
if (result == null)
{
label1.Text = " no decode";
}
else
{
label4.Text = result.Text;
label1.Text = dataDecrypted;
capture.Dispose();
}
}
} // end function Main
private void btnStart_Click(object sender, EventArgs e)
{
if (capture == null)
{
try
{
capture = new Capture(); // **the exption thown here**
}
catch (NullReferenceException exception)
{
MessageBox.Show(exception.Message);
}
}
if (capture != null)
{
if (Capturing)
{
btnStart.Text = "Start Capture";
Application.Idle -= Mains;
}
else
{
btnStart.Text = "Stop Capture";
Application.Idle += Mains;
}
Capturing = !Capturing;
}
}
private void Release()
{
if (capture != null)
capture.Dispose();
}}
If you want to host WinForm in WPF, you need to use host control System.Windows.Forms.Integration.WindowsFormsHost
WPF provides many controls with a rich feature set. However, you may
sometimes want to use Windows Forms controls on your WPF pages. For
example, you may have a substantial investment in existing Windows
Forms controls, or you may have a Windows Forms control that provides
unique functionality.
Example code
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// Create the interop host control.
System.Windows.Forms.Integration.WindowsFormsHost host =
new System.Windows.Forms.Integration.WindowsFormsHost();
// Create the MaskedTextBox control.
MaskedTextBox mtbDate = new MaskedTextBox("00/00/0000");
// Assign the MaskedTextBox control as the host control's child.
host.Child = mtbDate;
// Add the interop host control to the Grid
// control's collection of child controls.
this.grid1.Children.Add(host);
}
Check =>
http://msdn.microsoft.com/en-us/library/ms751761.aspx