How to update a windows form app (via LAN) using c#? - c#

I have a simple windows form application which I want to enable auto update feature (without using any third party app), so I add this code to the Form Load event of the app (the form has a label called label1 and its text is in the form v1.1)
XDocument doc=XDocument.Load(#"\\PC-10\TEST Update\share\checkver.xml");
double chkver=Convert.ToDouble(doc.Descendants("version").First().Value);
double currver=Convert.ToDouble(label1.Text.Substring(1,3));
if (chkver>currver) {
string exePath = Application.ExecutablePath;
string x=exePath.Substring(0,exePath.Length-10)+"\\updater.exe";
Process.Start(x);
this.Close();
}
The checkver.xml is a xml file located on the same folder as the updated myapp.exe and the updater.exe is located on the folder where the actual running app myapp.exe is i.e. Program Files
checkver.xml:
<?xml version="1.0"?>
<myapp>
<version>1.2</version>
</myapp>
updater.exe:
Console.WriteLine("Updating the app...please wait!");
string exePath = System.Reflection.Assembly.GetEntryAssembly().Location;
string x=exePath.Substring(0,exePath.Length-12);
File.Copy(#"\\PC-10\TEST Update\share\myapp.exe", x+"\\myapp.exe",true);
Console.WriteLine("Update completed!");
Process.Start(x+"\\myapp.exe");
When I run this from the actual projects bin folder it runs fine but when I create a setup file and install it on Program Files I get an error
System.UnauthorizedAccessException: Access to the path ...
and a message updater has stopped working.
Why is this happening?
Also is there a way to make this process faster(specially the update checking part)?

First thing I would do is check if myapp.exe is running with elevated privileges or not:
private static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
Run updater.exe.
if(IsAdministrator())
{
//.......
if (chkver>currver)
{
string exePath = Application.ExecutablePath;
string x=exePath.Substring(0,exePath.Length-10)+"\\updater.exe";
ProcessStartInfo info = new ProcessStartInfo(x);
info.UseShellExecute = true;
info.Verb = "runas";
Process.Start(info);
Environment.Exit(1); //Use .Exit(1) instead of this.Close();
}
}

I simply added a app.manifest file to my project like below
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel element will disable file and registry virtualization.
Remove this element if your application requires this virtualization for backwards
compatibility.
-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on and is
is designed to work with. Uncomment the appropriate elements and Windows will
automatically selected the most compatible environment. -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
</application>
</compatibility>
<!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config. -->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
-->
<!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>
It seems to solve the issue I had...but not 100% sure whether it is the right solution....

Related

WinForms: why form is not scaled correctly if started on the secondary display which is non-100% scaled? [duplicate]

I have created a WinForm along with a Label in Visual Studio 2022:
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
Designer:
namespace WinFormsApp1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#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()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.MaximumSize = new System.Drawing.Size(200, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(197, 39);
this.label1.TabIndex = 0;
this.label1.Text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(369, 115);
this.Controls.Add(this.label1);
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
}
}
App.manifest:
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel element will disable file and registry virtualization.
Remove this element if your application requires this virtualization for backwards
compatibility.
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config.
Makes the application long-path aware. See https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation -->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>-->
<!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<System.Windows.Forms.ApplicationConfigurationSection>
<add key="DpiAware" value="true" />
<add key="DpiAwareness" value="PerMonitorV2" />
<add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
</System.Windows.Forms.ApplicationConfigurationSection>
</configuration>
Program.cs:
namespace WinFormsApp1
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}
When run the app, on a 100% (96Dpi) screen:
However, when I move to a larger-scaled screen (175%):
What am I missing to have a proper scaled label on both screens?

Why my label is not scaling properly on DPI change?

I have created a WinForm along with a Label in Visual Studio 2022:
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
}
}
Designer:
namespace WinFormsApp1
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#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()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
this.label1.Location = new System.Drawing.Point(12, 9);
this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
this.label1.MaximumSize = new System.Drawing.Size(200, 0);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(197, 39);
this.label1.TabIndex = 0;
this.label1.Text = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.ClientSize = new System.Drawing.Size(369, 115);
this.Controls.Add(this.label1);
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Label label1;
}
}
App.manifest:
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC Manifest Options
If you want to change the Windows User Account Control level replace the
requestedExecutionLevel node with one of the following.
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
Specifying requestedExecutionLevel element will disable file and registry virtualization.
Remove this element if your application requires this virtualization for backwards
compatibility.
-->
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- A list of the Windows versions that this application has been tested on
and is designed to work with. Uncomment the appropriate elements
and Windows will automatically select the most compatible environment. -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />
</application>
</compatibility>
<!-- Indicates that the application is DPI-aware and will not be automatically scaled by Windows at higher
DPIs. Windows Presentation Foundation (WPF) applications are automatically DPI-aware and do not need
to opt in. Windows Forms applications targeting .NET Framework 4.6 that opt into this setting, should
also set the 'EnableWindowsFormsHighDpiAutoResizing' setting to 'true' in their app.config.
Makes the application long-path aware. See https://docs.microsoft.com/windows/win32/fileio/maximum-file-path-limitation -->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>-->
<!-- Enable themes for Windows common controls and dialogs (Windows XP and later) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>
App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<System.Windows.Forms.ApplicationConfigurationSection>
<add key="DpiAware" value="true" />
<add key="DpiAwareness" value="PerMonitorV2" />
<add key="EnableWindowsFormsHighDpiAutoResizing" value="true" />
</System.Windows.Forms.ApplicationConfigurationSection>
</configuration>
Program.cs:
namespace WinFormsApp1
{
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
// To customize application configuration such as set high DPI settings or default font,
// see https://aka.ms/applicationconfiguration.
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
ApplicationConfiguration.Initialize();
Application.Run(new Form1());
}
}
}
When run the app, on a 100% (96Dpi) screen:
However, when I move to a larger-scaled screen (175%):
What am I missing to have a proper scaled label on both screens?

Error API key not found when i am trying to add google map to Xamarin

I'm trying to add Google Maps in Xamarin Forms app but when I run it
this error occurred:
Java.Lang.RuntimeException
Message=API key not found. Check that is in the element of AndroidManifest.xml
Java.Lang.RuntimeException: 'API key not found. Check that is in the element of AndroidManifest.xml'
Erorr message
Is there any way to know this API is active?
make sure, it is inside the application element and they spelling is correct.
Check this docs page:
https://learn.microsoft.com/en-us/xamarin/android/platform/maps-and-location/maps/maps-api#-specify-the-required-permissions
Scroll down a bit to the large code block after "The following snippet is an example of the settings that must be added to AndroidManifest.XML:" and make sure to replace YOUR_API_KEY with your actual api key.
Copied from link (in case it goes away):
The following snippet is an example of the settings that must be added to AndroidManifest.XML:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionName="4.5"
package="com.xamarin.docs.android.mapsandlocationdemo2"
android:versionCode="6">
<uses-sdk android:minSdkVersion="23" android:targetSdkVersion="28" />
<!-- Google Maps for Android v2 requires OpenGL ES v2 -->
<uses-feature android:glEsVersion="0x00020000" android:required="true" />
<!-- Necessary for apps that target Android 9.0 or higher -->
<uses-library android:name="org.apache.http.legacy" android:required="false" />
<!-- Permission to receive remote notifications from Google Play Services -->
<!-- Notice here that we have the package name of our application as a prefix on the permissions. -->
<uses-permission android:name="<PACKAGE NAME>.permission.MAPS_RECEIVE" />
<permission android:name="<PACKAGE NAME>.permission.MAPS_RECEIVE" android:protectionLevel="signature" />
<!-- These are optional, but recommended. They will allow Maps to use the My Location provider. -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application android:label="#string/app_name">
<!-- Put your Google Maps V2 API Key here. -->
<meta-data android:name="com.google.android.maps.v2.API_KEY" android:value="YOUR_API_KEY" />
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
<!-- Necessary for apps that target Android 9.0 or higher -->
<uses-library android:name="org.apache.http.legacy" android:required="false" />
</application>
</manifest>
Your API keys can be found in your Google Cloud Platform Console
Here's the link : https://console.cloud.google.com/apis/credentials
You can check for the status of your "Maps SDK for Android" by searching for it in the GCP console's API Library : https://console.cloud.google.com/apis/library

Windows Classic-style button in WPF MessageBox! [duplicate]

How to apply the default Windows style to the standard MessageBox in WPF?
For example, when I execute next code:
MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButton.OKCancel,
MessageBoxImage.Exclamation);
I'm getting message box:
But in WinForms everything is OK with style:
MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButtons.OKCancel,
MessageBoxIcon.Exclamation);
According to this page, WPF picks up the old styles for some of the controls.
To get rid of it, you have to create a custom app.manifest file (Add -> New item -> Application Manifest File) and paste the following code in it (right after the /trustInfo - Tag ):
<!-- Activate Windows Common Controls v6 usage (XP and Vista): -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Then you have to compile your solution with this app.manifest (set it in the project properties -> Application -> Point to the new manifest in "Icons and manifest").
If you start your application now it should look like the WinForms- MessageBox.
as how i triggered it, "redirecting" the usual references to the Forms ones (they work the same, but are named differently):
using MessageBox = System.Windows.Forms.MessageBox;
using MessageBoxImage = System.Windows.Forms.MessageBoxIcon;
using MessageBoxButton = System.Windows.Forms.MessageBoxButtons;
using MessageBoxResult = System.Windows.Forms.DialogResult;
namespace ... class ...
public MainWindow()
{
InitializeComponent();
System.Windows.Forms.Application.EnableVisualStyles();
}
public void do()
{
// updated style, but good syntax for a later solution
MessageBox.Show("Some Message", "DEBUG", MessageBoxButton.OK, MessageBoxImage.Question);
}
... the manifest solution did not work for me.
The reason that the WinForms one works the way that it does is because visual styles are turned on (i.e. using Common Controls v6) in its Main function. If you remove the call to System.Windows.Forms.Application.EnableVisualStyles(), then the WinForms Message Box will look just like the WPF one.
This doesn't happen for a WPF app, possibly because all of the WPF controls are rendered so there is no need to use the new version of Common Controls.
You might try calling EnableVisualStyles() somewhere in the start up of your WPF application. I don't know if it will work or not, but it's worth a try. This will require a reference to System.Windows.Forms, though.
Also, for WPF I would recommmend using the Extended WPF Toolkit which has a WPF messagebox
Create a new manifest and paste this:
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
</application>
</compatibility>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>

WPF MessageBox window style

How to apply the default Windows style to the standard MessageBox in WPF?
For example, when I execute next code:
MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButton.OKCancel,
MessageBoxImage.Exclamation);
I'm getting message box:
But in WinForms everything is OK with style:
MessageBox.Show("Hello Stack Overflow!", "Test", MessageBoxButtons.OKCancel,
MessageBoxIcon.Exclamation);
According to this page, WPF picks up the old styles for some of the controls.
To get rid of it, you have to create a custom app.manifest file (Add -> New item -> Application Manifest File) and paste the following code in it (right after the /trustInfo - Tag ):
<!-- Activate Windows Common Controls v6 usage (XP and Vista): -->
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"/>
</dependentAssembly>
</dependency>
Then you have to compile your solution with this app.manifest (set it in the project properties -> Application -> Point to the new manifest in "Icons and manifest").
If you start your application now it should look like the WinForms- MessageBox.
as how i triggered it, "redirecting" the usual references to the Forms ones (they work the same, but are named differently):
using MessageBox = System.Windows.Forms.MessageBox;
using MessageBoxImage = System.Windows.Forms.MessageBoxIcon;
using MessageBoxButton = System.Windows.Forms.MessageBoxButtons;
using MessageBoxResult = System.Windows.Forms.DialogResult;
namespace ... class ...
public MainWindow()
{
InitializeComponent();
System.Windows.Forms.Application.EnableVisualStyles();
}
public void do()
{
// updated style, but good syntax for a later solution
MessageBox.Show("Some Message", "DEBUG", MessageBoxButton.OK, MessageBoxImage.Question);
}
... the manifest solution did not work for me.
The reason that the WinForms one works the way that it does is because visual styles are turned on (i.e. using Common Controls v6) in its Main function. If you remove the call to System.Windows.Forms.Application.EnableVisualStyles(), then the WinForms Message Box will look just like the WPF one.
This doesn't happen for a WPF app, possibly because all of the WPF controls are rendered so there is no need to use the new version of Common Controls.
You might try calling EnableVisualStyles() somewhere in the start up of your WPF application. I don't know if it will work or not, but it's worth a try. This will require a reference to System.Windows.Forms, though.
Also, for WPF I would recommmend using the Extended WPF Toolkit which has a WPF messagebox
Create a new manifest and paste this:
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app"/>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
</requestedPrivileges>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
</application>
</compatibility>
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
</assembly>

Categories