WinForms - Show notification count in app launcher Icon - winforms

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.

Related

Show an image from a URL in WinForms PictureBox

Hi I have a WinForms project targetting .net core. I am trying to load an image from a URL, but all I am getting is this:
Inside a UserControl I have added a PictureBox (pic1) and a Button.
Added the following as an example to the click event of the button:
pic1.LoadAsync("https://images.pexels.com/photos/4815143/pexels-photo-4815143.jpeg");
also
pic1.ImageLocation = "https://images.pexels.com/photos/4815143/pexels-photo-4815143.jpeg";
Have tried with different URLs
Any ideas what is wrong?
Edit
I've tried an alternative option, something seems to be getting stuck on DownloadData
using (WebClient webClient = new WebClient())
{
byte[] data = webClient.DownloadData("https://images.pexels.com/photos/4815143/pexels-photo-4815143.jpg");
using (MemoryStream mem = new MemoryStream(data))
{
using (var yourImage = Image.FromStream(mem))
{
}
}
}

Is there a Geopoint class available for Winforms (or an Analogue thereof)?

In my UWP app, I use a Geopoint class:
using Windows.Devices.Geolocation;
. . .
List<Geopoint> locations;
In a Winforms app, this is not available - Geopoint is not recognized. Is there an analogous class available for Winforms apps?
The same is true for the BasicGeoposition object - not recognized.
UPDATE
I want the GeoPoint and BasicGeoposition classes so I can do things like this:
BasicGeoposition location = new BasicGeoposition();
location.Latitude = 36.59894360222391; // Monterey == 36.6002° N
location.Longitude = -121.8616426604813; // Monterey == 121.8947° W (West is negative)
Geopoint geop = new Geopoint(location);
await map.TrySetSceneAsync(MapScene.CreateFromLocation(geop));
cmbxZoomLevels.SelectedIndex = Convert.ToInt32(map.ZoomLevel - 1);
map.Style = MapStyle.Aerial3DWithRoads;
UPDATE 2
I tried the code provided in the answer:
this.UserControl1.myMap.AnimationLevel = AnimationLevel.Full;
this.userControl11.myMap.Loaded += MyMap_Loaded;
...but it won't compile. I don't have a UserControl11 (which is what the answer's code has), but I do have a UserControl1, yet it is not recognized:
This is the XAML in question (Bing Maps key obfuscated):
<UserControl x:Class="MyMaps.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:m="clr-namespace:Microsoft.Maps.MapControl.WPF;assembly=Microsoft.Maps.MapControl.WPF">
<Grid>
<m:Map CredentialsProvider="Gr8GooglyMoogly" x:Name="myMap" />
</Grid>
</UserControl>
To set the view of the Bing Maps WPF control, you can use SetView method. The method have different overloads, for example you can pass a Location(which you create based on the latitude and longitude of your desired location) and a zoom-level to the method like this:
var location = new Location(47.604, -122.329);
this.userControl11.myMap.SetView(location, 12);
Same can be achieved by setting Center and ZoomLevel.
Download or Clone the example
You can download or close the working example from here:
Clone r-aghaei/WinFormsWpfBingMaps
Download master.zip
Step by Step Example - Zoom into Seattle as initial view
Follow instructions in this post to create a Windows Forms project which uses WPF Bing Maps Control.
Handle the Load event of the Form and use the following code:
private void Form1_Load(object sender, EventArgs e)
{
this.userControl11.myMap.AnimationLevel = AnimationLevel.Full;
this.userControl11.myMap.Loaded += MyMap_Loaded;
}
private void MyMap_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
var location = new Location(47.604, -122.329);
this.userControl11.myMap.SetView(location, 12);
}
Make sure you use using Microsoft.Maps.MapControl.WPF;.
As a result, the map zooms in Seattle as center location:
More information:
You may want to take a look at the following links for more information:
How can I add a Bing Maps Component to my C# Winforms app?
Bing Maps WPF Control
Developing with the Bing Maps WPF Control
Bing Maps WPF Control API Reference
For those who are looking to use Windows Community Toolkit Map Control which is different from Bing Maps WPF Control, you can follow these steps to use Windows Community Toolkit Map Control for Windows Forms.
Note: Windows 10 (introduced v10.0.17709.0) is a prerequisite.
Create a Windows Forms Application (.NET Framework >=4.6.2 - I tried myself with 4.7.2)
Install Microsoft.Toolkit.Forms.UI.Controls NuGet package.
Add an app.manifest file: Right-click on project → Add New Item → Choose Application Manifest File (Windows Only) which is located under General node.
Open the app.manifest file and uncomment the supportedOS under <!-- Windows 10 -->:
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
Handle the Load event of your form and add the following code:
private void Form1_Load(object sender, EventArgs e)
{
var map = new MapControl();
map.Dock = DockStyle.Fill;
map.MapServiceToken = "YOUR KEY";
map.LoadingStatusChanged += async (obj, args) =>
{
if (map.LoadingStatus == MapLoadingStatus.Loaded)
{
var cityPosition = new BasicGeoposition() {
Latitude = 47.604, Longitude = -122.329 };
var cityCenter = new Geopoint(cityPosition);
await map.TrySetViewAsync(cityCenter, 12);
}
};
this.Controls.Add(map);
}
Also make sure you include required usings:
using Microsoft.Toolkit.Forms.UI.Controls;
using Microsoft.Toolkit.Win32.UI.Controls.Interop.WinRT;
Note 1: I was unable to add the control in designer because of an exception on design-time when I tried to drop the control on form, so I decided to use add it at run-time.
Note 2: You need to Get a Key to use map; however for test purpose you may ignore getting the key.
Run your application and see the result:
More information
MapControl for Windows Forms and WPF
Source code: Microsoft.Toolkit.Forms.UI.Controls.MapControl
WinForms control is a wrapper around WPF Windows.UI.Xaml.Controls.Maps.MapControl
Display maps with 2D, 3D, and Streetside views

Cefsharp OffScreen set RequestContext

I want to define a new RequestContext when using CefSharp OffScreen to prevent multiple browser instances sharing the same information (e.g. cookies).
I can simply do that with CefSharp WinForms like that:
RequestContextSettings requestContextSettings = new RequestContextSettings();
requestContextSettings.PersistSessionCookies = false;
requestContextSettings.PersistUserPreferences = false;
WebBrowser.RequestContext = new RequestContext(requestContextSettings);
But the RequestContext is readonly in the offscreen variant.
See http://cefsharp.github.io/api/57.0.0/html/P_CefSharp_OffScreen_ChromiumWebBrowser_RequestContext.htm
Why is that so? And are there other ways to accomplish it?

WPF native windows 10 toasts

Using .NET WPF and Windows 10, is there a way to push a local toast notification onto the action center using c#? I've only seen people making custom dialogs for that but there must be a way to do it through the os.
You can use a NotifyIcon from System.Windows.Forms namespace like this:
class Test
{
private readonly NotifyIcon _notifyIcon;
public Test()
{
_notifyIcon = new NotifyIcon();
// Extracts your app's icon and uses it as notify icon
_notifyIcon.Icon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
// Hides the icon when the notification is closed
_notifyIcon.BalloonTipClosed += (s, e) => _notifyIcon.Visible = false;
}
public void ShowNotification()
{
_notifyIcon.Visible = true;
// Shows a notification with specified message and title
_notifyIcon.ShowBalloonTip(3000, "Title", "Message", ToolTipIcon.Info);
}
}
This should work since .NET Framework 1.1. Refer to this MSDN page for parameters of ShowBalloonTip.
As I found out, the first parameter of ShowBalloonTip (in my example that would be 3000 milliseconds) is generously ignored. Comments are appreciated ;)
I know this is an old post but I thought this might help someone that stumbles on this as I did when attempting to get Toast Notifications to work on Win 10.
This seems to be good outline to follow -
Send a local toast notification from desktop C# apps
I used that link along with this great blog post- Pop a Toast Notification in WPF using Win 10 APIs
to get my WPF app working on Win10. This is a much better solution vs the "old school" notify icon because you can add buttons to complete specific actions within your toasts even after the notification has entered the action center.
Note- the first link mentions "If you are using WiX" but it's really a requirement. You must create and install your Wix setup project before you Toasts will work. As the appUserModelId for your app needs to be registered first. The second link does not mention this unless you read my comments within it.
TIP- Once your app is installed you can verify the AppUserModelId by running this command on the run line shell:appsfolder . Make sure you are in the details view, next click View , Choose Details and ensure AppUserModeId is checked. Compare your AppUserModelId against other installed apps.
Here's a snipit of code that I used. One thing two note here, I did not install the "Notifications library" mentioned in step 7 of the first link because I prefer to use the raw XML.
private const String APP_ID = "YourCompanyName.YourAppName";
public static void CreateToast()
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText02);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("This is my title!!!!!!!!!!"));
stringElements[1].AppendChild(toastXml.CreateTextNode("This is my message!!!!!!!!!!!!"));
// Specify the absolute path to an image
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + #"\Your Path To File\Your Image Name.png";
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
imageElements[0].Attributes.GetNamedItem("src").NodeValue = filePath;
// Change default audio if desired - ref - https://learn.microsoft.com/en-us/uwp/schemas/tiles/toastschema/element-audio
XmlElement audio = toastXml.CreateElement("audio");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Reminder");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.IM");
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Mail"); // sounds like default
//audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call7");
audio.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Call2");
//audio.SetAttribute("loop", "false");
// Add the audio element
toastXml.DocumentElement.AppendChild(audio);
XmlElement actions = toastXml.CreateElement("actions");
toastXml.DocumentElement.AppendChild(actions);
// Create a simple button to display on the toast
XmlElement action = toastXml.CreateElement("action");
actions.AppendChild(action);
action.SetAttribute("content", "Show details");
action.SetAttribute("arguments", "viewdetails");
// Create the toast
ToastNotification toast = new ToastNotification(toastXml);
// Show the toast. Be sure to specify the AppUserModelId
// on your application's shortcut!
ToastNotificationManager.CreateToastNotifier(APP_ID).Show(toast);
}
UPDATE
This seems to be working fine on windows 10
https://msdn.microsoft.com/library/windows/apps/windows.ui.notifications.toastnotificationmanager.aspx
you will need to add these nugets
Install-Package WindowsAPICodePack-Core
Install-Package WindowsAPICodePack-Shell
Add reference to:
C:\Program Files (x86)\Windows Kits\8.1\References\CommonConfiguration\Neutral\Windows.winmd
And
C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETCore\v4.5\System.Runtime.WindowsRuntime.dll
And use the following code:
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText04);
// Fill in the text elements
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
for (int i = 0; i < stringElements.Length; i++)
{
stringElements[i].AppendChild(toastXml.CreateTextNode("Line " + i));
}
// Specify the absolute path to an image
string imagePath = "file:///" + Path.GetFullPath("toastImageAndText.png");
XmlNodeList imageElements = toastXml.GetElementsByTagName("image");
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier("Toast Sample").Show(toast);
The original code can be found here: https://www.michaelcrump.net/pop-toast-notification-in-wpf/
I managed to gain access to the working API for windows 8 and 10 by referencing
Windows.winmd:
C:\Program Files (x86)\Windows Kits\8.0\References\CommonConfiguration\Neutral
This exposes Windows.UI.Notifications.
You can have a look at this post for creating a COM server that is needed in order to have notifications persisted in the AC with Win32 apps https://blogs.msdn.microsoft.com/tiles_and_toasts/2015/10/16/quickstart-handling-toast-activations-from-win32-apps-in-windows-10/.
A working sample can be found at https://github.com/WindowsNotifications/desktop-toasts

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

Resources