Cefsharp Winform shows images blurred - winforms

Tools used : .net framework 4.7.2, Windows 7 x64, Visual Studio 2019
I'm creating a Cefsharp Winform browser.
It works as an simple GUI for my asp.net core app.
The problem stands on the fact that the pictures are very blurred.
If i use firefox/chrome the pictures are high quality and clean.
My Form1.cs :
public ChromiumWebBrowser browser;
public void InitBrowser()
{
CefSharpSettings.WcfEnabled = true;
var settings = new CefSettings();
//Absolute path to your applications executable
settings.BrowserSubprocessPath = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;
Cef.EnableHighDPISupport();
Cef.RefreshWebPlugins();
Cef.Initialize(new CefSettings());
browser = new ChromiumWebBrowser("https://localhost:5001")
{
MenuHandler = new CustomMenuHandler()
};
this.Controls.Add(browser);
browser.Dock = DockStyle.Fill;
}
public Form1()
{
InitializeComponent();
InitBrowser();
}
the debug_.log :
[0529/224714.592:ERROR:gpu_init.cc(426)] Passthrough is not supported, GL is disabled
[0529/225010.059:WARNING:dns_config_service_win.cc(712)] Failed to read DnsConfig.
What's wrong with this code?

Related

Webcam for WPF .NET Core 3.1

I've tried a lot of dependencies in my project for webcam, including :
OpenCVSharp
WpfWebcamControl
WebcamCapturer.Core
But seems like all of those dependencies does not fully compatible with my project.
My current project dependencies :
Microsoft.NETCore.App v3.1
Microsoft.WindowsDesktop.App.WPF
Is there any compatible webcam dependency for WPF .NET Core v3.1 ?
These packages are incompatible with .NET Core 3.1.
WpfWebcamControl (>= .NET Framework 4.6)
WebcamCapturer.Core (>= .NET Framework 4.7.2)
For OpenCV, you might be using the wrong package, as it is indeed compatible with .NET Core 3.1.
OpenCVSharp (.NET Framework)
OpenCVSharp4 (>= .NET Framework 4.6.2, >= .NET Standard 2.0, >= .NET Core 2.1)
For more info and packages, see GitHub and a short tutorial here.
Please note that the OpenCVSharp4 package is the core package, depending on your use-case, you might instead use OpenCvSharp4.Windows and optionally OpenCvSharp4.WpfExtensions. Please refer to the project page GitHub and the Wiki for more information.
A bit of sharing how I done it based on the accepted answer by #thatguy
first, Installing OpenCvSharp4.Windows and OpenCvSharp4.WpfExtensions into your wpf .NET Core application.
Then I put <Image x:Name="image1" Width="400" Height="300" /> in my xaml file
and use WriteableBitmapConverter.ToWriteableBitmap to keep updating my image
bellow is my code behind
public partial class MainWindow : System.Windows.Window
{
private System.Timers.Timer MyDataTimer;
FrameSource frameSource = Cv2.CreateFrameSource_Camera(0);
public MainWindow()
{
InitializeComponent();
MyDataTimer = new System.Timers.Timer();
MyDataTimer.Elapsed += new ElapsedEventHandler(MyDataTimer_Elapsed);
MyDataTimer.Enabled = true;
MyDataTimer.Interval = 1 * 1;
MyDataTimer.Start();
}
private void MyDataTimer_Elapsed(object source, ElapsedEventArgs e)
{
try
{
MyDataTimer.Stop();
MyDataTimer.Interval = 1 * 1;
this.Dispatcher.Invoke(new Action(LoadImages));
MyDataTimer.Start();
}
catch (Exception ex)
{
}
finally
{
MyDataTimer.Start();
}
}
private void LoadImages()
{
using (var mat = new Mat())
{
frameSource.NextFrame(mat);
var wb = WriteableBitmapConverter.ToWriteableBitmap(mat);
image1.Source = null;
image1.Source = wb;
}
}
}
Hope this would help!

WinForms - Show notification count in app launcher Icon

In my WinForms application, I want to display the notifications count in the app launcher icon.
How can this be achieved ?
I believe this is what you're asking for, unfortunately it is in WPF. Winforms doesn't provide a way to do that. You need to P/Invoke manually.
Download Windows 7 API Code Pack - Shell
and use the following.
private void SetTaskBarOverlay()
{
string notificationCount = "3"; //To do: Add this as a parameter
var bmp = new Bitmap(32, 32);
using (Graphics g = Graphics.FromImage(bmp))
{
g.FillEllipse(Brushes.Blue, new Rectangle(Point.Empty, bmp.Size));
g.DrawString(notificationCount, new Font("Sans serif", 25, GraphicsUnit.Point),
Brushes.White, new Rectangle(Point.Empty, bmp.Size));
}
var overlay = Icon.FromHandle(bmp.GetHicon());
TaskbarManager.Instance.SetOverlayIcon(overlay, "");
}
private void RemoveTaskBarOverlay()
{
TaskbarManager.Instance.SetOverlayIcon(null, "");
}
You may alter the painting code to achieve the desired effect.

passing values between silverlight applications

I have created a Silverlight Business Application which runs as my main silverlight page. For each hyperlink button on my "menu" I launch another Silverlight Application which is created as a different project in Visual Studio. These are non-Business Applications.
Everything is working well. However I'm trying to pass a value from my main SL application to the SL application inside.
I have been googling a lot and cannot find an answer.
As I understand the InitParam is used between ASP and SL, and not between SL apps.
Since the App config is launched for the first SL app and the app config for the second application in never lauched, I'm not able to use that (thats at least my understanding)
The value I want to pass is the login name and role, which is possible to get from webcontext in the Silverlight Business application, but I'm unable to get webcontext in the non-Business application which run inside.
This is how I launch my SL app inside the main SL app:
public Customers()
{
InitializeComponent();
this.Title = ApplicationStrings.CustomersPageTitle;
if (WebContext.Current.User.IsInRole("Users") || WebContext.Current.User.IsInRole("Administrators"))
{
WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("customers.xap", UriKind.Relative));
}
}
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
string appManifest = new StreamReader(Application.GetResourceStream(new StreamResourceInfo(e.Result, null),
new Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd();
XElement deploymentRoot = XDocument.Parse(appManifest).Root;
List<XElement> deploymentParts =
(from assemblyParts in deploymentRoot.Elements().Elements() select assemblyParts).ToList();
Assembly asm = null;
AssemblyPart asmPart = new AssemblyPart();
foreach (XElement xElement in deploymentParts)
{
string source = xElement.Attribute("Source").Value;
StreamResourceInfo streamInfo = Application.GetResourceStream(new StreamResourceInfo(e.Result, "application/binary"), new Uri(source, UriKind.Relative));
if (source == "customers.dll")
{
asm = asmPart.Load(streamInfo.Stream);
}
else
{
asmPart.Load(streamInfo.Stream);
}
}
UIElement myData = asm.CreateInstance("customers.MainPage") as UIElement;
stackCustomers.Children.Add(myData);
stackCustomers.UpdateLayout();
}
Anyone?
i agree with ChrisF ,I think that Prism or MEF can resolve you problem.
any way,do some search on the web and look for these two classes:
**
LocalMessageSender
LocalMessageReceiver
**
good luck

silverlight 4, dynamically loading xap modules

I know that it is possible to load xap modules dynamically using Prism or MEF framework. However, I'd like not to use those frameworks; instead load my xap files manually. So, I created the following class (adapted from internet):
public class XapLoader
{
public event XapLoadedEventHandler Completed;
private string _xapName;
public XapLoader(string xapName)
{
if (string.IsNullOrWhiteSpace(xapName))
throw new ArgumentException("Invalid module name!");
else
_xapName = xapName;
}
public void Begin()
{
Uri uri = new Uri(_xapName, UriKind.Relative);
if (uri != null)
{
WebClient wc = new WebClient();
wc.OpenReadCompleted += onXapLoadingResponse;
wc.OpenReadAsync(uri);
}
}
private void onXapLoadingResponse(object sender, OpenReadCompletedEventArgs e)
{
if ((e.Error == null) && (e.Cancelled == false))
initXap(e.Result);
if (Completed != null)
{
XapLoadedEventArgs args = new XapLoadedEventArgs();
args.Error = e.Error;
args.Cancelled = e.Cancelled;
Completed(this, args);
}
}
private void initXap(Stream stream)
{
string appManifest = new StreamReader(Application.GetResourceStream(
new StreamResourceInfo(stream, null), new Uri("AppManifest.xaml",
UriKind.Relative)).Stream).ReadToEnd();
XElement deploy = XDocument.Parse(appManifest).Root;
List<XElement> parts = (from assemblyParts in deploy.Elements().Elements()
select assemblyParts).ToList();
foreach (XElement xe in parts)
{
string source = xe.Attribute("Source").Value;
AssemblyPart asmPart = new AssemblyPart();
StreamResourceInfo streamInfo = Application.GetResourceStream(
new StreamResourceInfo(stream, "application/binary"),
new Uri(source, UriKind.Relative));
asmPart.Load(streamInfo.Stream);
}
}
}
public delegate void XapLoadedEventHandler(object sender, XapLoadedEventArgs e);
public class XapLoadedEventArgs : EventArgs
{
public Exception Error { get; set; }
public bool Cancelled { get; set; }
}
The above code works fine; I can load any xap the following way:
XapLoader xapLoader = new XapLoader("Sales.xap");
xapLoader.Completed += new XapLoadedEventHandler(xapLoader_Completed);
xapLoader.Begin();
Now, I have a UserControl called InvoiceView in the Sales.xap project, so I would like to instantiate the class. In the current project (Main.xap) I added reference to Sales.xap project, however, since I load it manually I set "Copy Local = False". But when executed, the following code throws TypeLoadException:
Sales.InvoiceView view = new Sales.InvoiceView();
It seems the code can't find InvoiceView class. But I checked that XapLoader's initXap() method was successfully executed. So why the code can't find InvoiceView class? Can someone help me with this problem?
This is based on the asker's self-answer below, rather than the question.
If you delete a project/module the output DLLs/XAP files do hang around. If you click the "show all files" button you will see some these left-over output files in your clientbin, bin and obj folders of related projects.
You can delete them individually from the project, or, when in doubt, search for all BIN and OBJ (e.g. using desktop explorer) and delete all those folders. The BIN/CLIENTBIN/OBJ folders will be recreated when needed (this the job that the "clean" option in Visual Studio should have done!)
Hope this helps.
Ok, I found the cause. The above code works. After creating a new silverlight project (Sales.xap) I happened to compile my solution once. Then I deleted App class in the Sales.xap and renamed default MainPage class to SalesView. However, no matter how many times I compile my solution, Visual Studio's development web server was loading the first version of Sales.xap (where from?), so my code couldn't find SalesView. In my host Asp.Net project I set development server's port to a different port number, and the problem gone. So the problem was with Visual Studio's development server. Apparently it is keeping compiled xap files in some temporary folder, and doesn't always update those xap files when source code changed.
What I do to avoid such problems when executing freshly compiled Silverlight is clear the browser cache, chrome even has a clear silverlight cache ;)
this XAP Cache phenomena is often due to the visual studio embedded web server (ASP.NET Development Server).
Just stop the occurence of this server and the cache will be cleared.
Start again your project and the latest build of your xap is called.

Debugging silverlight in a WPF app

I am developing a WPF app that contains a webbrowser control that loads a silverlight application. I would like to be able to launch the app from visual studio (F5) and have the debugger attach to the silverlight code. However, I've not had any luck with this.
The best I can currently do is to launch the app without attaching, then once it is up and running, attach to the process manually with silverlight as the specified type of code to debug, and this works. (When I cause the web browser control to load the silverlight app, it will hit breakpoints in my silverlight code). I've written some macros to automate this launching/attaching somewhat, but it still isn't the best.
I've tried specifying the WPF app as the external program to run when launching/debugging the silverlight app, but Visual Studio attaches to the process wanting to debug the managed .NET code.
Any ideas? Ideally, I would really like to attach to the process and debug both the managed .NET and the silverlight code, but I don't think this is possible. I'd really like to automatically be attached to the silverlight code at launch so that I can easily debug all issues with the silverlight app, including those that occur on load.
Thanks for your ideas Brandorf and fatty. Brandorf's almost gets me to where I wanted to go, but does require that my SL app be capable of running on its own. I really want to have only the one app, which is both wpf and silverlight, with the SL side being debugged.
A long time after I asked this question (I forgot I had asked it here), I actually pieced together a solution that I'm really happy with. I use visual studio automation within the WPF/.NET side of my app, to find all running instances of visual studio, figure out which one produced my exe (since it typically sits in a folder below the vcproj/sln folder), and then use visual studio automation to have that VS attach to the app, debugging silverlight code. After this is done, I then load my silverlight content.
It works really well. You end up with an app that goes and finds a debugger to attach to itself every time it runs (so you probably want this code only in a debug build, or somehow able to be turned off). So you just launch the app with ctrl-F5 (launch without debugging) from visual studio whenever you want to debug the silverlight side.
Here's my code:
#if DEBUG
using System;
using System.Collections.Generic;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO;
namespace Launcher
{
//The core methods in this class to find all running instances of VS are
//taken/inspired from
//http://www.codeproject.com/KB/cs/automatingvisualstudio.aspx
class DebuggingAutomation
{
[DllImport("ole32.dll")]
private static extern int GetRunningObjectTable(int reserved,
out UCOMIRunningObjectTable prot);
[DllImport("ole32.dll")]
private static extern int CreateBindCtx(int reserved,
out UCOMIBindCtx ppbc);
///<summary>
///Get a snapshot of the running object table (ROT).
///</summary>
///<returns>
///A hashtable mapping the name of the object
///in the ROT to the corresponding object
///</returns>
private static Hashtable GetRunningObjectTable()
{
Hashtable result = new Hashtable();
int numFetched;
UCOMIRunningObjectTable runningObjectTable;
UCOMIEnumMoniker monikerEnumerator;
UCOMIMoniker[] monikers = new UCOMIMoniker[1];
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
while (monikerEnumerator.Next(1, monikers, out numFetched) == 0)
{
UCOMIBindCtx ctx;
CreateBindCtx(0, out ctx);
string runningObjectName;
monikers[0].GetDisplayName(ctx, null, out runningObjectName);
object runningObjectVal;
runningObjectTable.GetObject(monikers[0], out runningObjectVal);
result[runningObjectName] = runningObjectVal;
}
return result;
}
/// <summary>
/// Get a table of the currently running instances of the Visual Studio .NET IDE.
/// </summary>
/// <param name="openSolutionsOnly">
/// Only return instances that have opened a solution
/// </param>
/// <returns>
/// A list of the ides (as DTE objects) present in
/// in the running object table to the corresponding DTE object
/// </returns>
private static List<EnvDTE.DTE> GetIDEInstances(bool openSolutionsOnly)
{
var runningIDEInstances = new List<EnvDTE.DTE>();
Hashtable runningObjects = GetRunningObjectTable();
IDictionaryEnumerator rotEnumerator = runningObjects.GetEnumerator();
while (rotEnumerator.MoveNext())
{
string candidateName = (string)rotEnumerator.Key;
if (!candidateName.StartsWith("!VisualStudio.DTE"))
continue;
EnvDTE.DTE ide = rotEnumerator.Value as EnvDTE.DTE;
if (ide == null)
continue;
if (openSolutionsOnly)
{
try
{
string solutionFile = ide.Solution.FullName;
if (!String.IsNullOrEmpty(solutionFile))
{
runningIDEInstances.Add(ide);
}
}
catch { }
}
else
{
runningIDEInstances.Add(ide);
}
}
return runningIDEInstances;
}
internal static void AttachDebuggerIfPossible()
{
if (System.Diagnostics.Debugger.IsAttached)
{
//Probably debugging host (Desktop .NET side), so don't try to attach to silverlight side
return;
}
var ides = GetIDEInstances(true);
var fullPathToAssembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
var potentials = new List<EnvDTE.DTE>();
foreach (var ide in ides)
{
var solutionPath = ide.Solution.FullName;
var topLevelSolutionDir = Path.GetDirectoryName(solutionPath);
var assemblyName = fullPathToAssembly;
if (assemblyName.StartsWith(topLevelSolutionDir, StringComparison.OrdinalIgnoreCase))
{
potentials.Add(ide);
}
}
EnvDTE.DTE chosenIde = null;
//If you have multiple ides open that can match your exe, you can come up with a scheme to pick a particular one
//(eg, put a file like solution.sln.pickme next to the solution whose ide you want to debug). If this is not a
//concern, just pick the first match.
if (potentials.Count > 0)
{
chosenIde = potentials[0];
}
var dbg = chosenIde != null ? (EnvDTE80.Debugger2)chosenIde.Debugger : null;
if (dbg != null)
{
var trans = dbg.Transports.Item("Default");
var proc = (EnvDTE80.Process2)dbg.GetProcesses(trans, System.Environment.MachineName).Item(Path.GetFileName(fullPathToAssembly));
var engines = new EnvDTE80.Engine[1];
engines[0] = trans.Engines.Item("Silverlight");
proc.Attach2(engines);
}
}
}
}
#endif
It's a bit of a shot in the dark, but assuming your silverlight app is capable of running on its own, you can, under your solution settings, set visual studio to start both apps together, and you should be attached to both of them.
If you can't add the Silverlight project to your solution (which will start debugging automatically), you might be able to make use of this tip. It will load both projects at the same time
http://saraford.net/2008/07/28/did-you-know-you-can-start-debugging-multiple-projects-268/

Resources