ShellExecuteEx function works in a different way in Windows 10? - c#

I'm trying to open info property of file.
In the previous versions of Windows, properties window was shown and then the control was given to next function in my code, but in Windows 10 function call stucks until I'm closing file properties with mouse click.
I wonder what have been changed in the new Windows version?
My code is below:
private const int SwShow = 5;
private const uint SeeMaskInvokeidlist = 12;
public static bool ShowFileProperties(string filename)
{
var info = new Shellexecuteinfo();
info.cbSize = Marshal.SizeOf(info);
info.lpVerb = "properties";
info.lpFile = filename;
info.nShow = SwShow;
info.fMask = SeeMaskInvokeidlist;
return ShellExecuteEx(ref info);
}
[DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern bool ShellExecuteEx(ref Shellexecuteinfo lpExecInfo);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct Shellexecuteinfo
{
public int cbSize;
public uint fMask;
public IntPtr hwnd;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpVerb;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpFile;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpParameters;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpDirectory;
public int nShow;
public IntPtr hInstApp;
public IntPtr lpIDList;
[MarshalAs(UnmanagedType.LPTStr)]
public string lpClass;
public IntPtr hkeyClass;
public uint dwHotKey;
public IntPtr hIcon;
public IntPtr hProcess;
}
static void Main(string[] args)
{
Console.WriteLine("Show file info.");
ShowFileProperties(args[0]);
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("File info was shown.");
}

Related

Programmatically set Brightness on Monitor via NVIDIA driver

i would like to have the possibility to change the monitors brightness from a .NET desktop application. (running on win7 with nvidia gpu)
i found this winapi function:
https://msdn.microsoft.com/en-us/library/windows/desktop/dd692972(v=vs.85).aspx
and there are some SO questions with examples, but calling this does nothing for me.
but i found that my nvidia control panel allows to adjust the brightness with a slider.
so i was wondering if there is an API to use this functionality? and if maybe someone has some sample code on how to access it?
I am running win7 with AMD card and following example has worked for me.
SetBrightness expects argument in 0-100 range.
I have only one monitor to test so I set brightness just for first one.
using System;
using System.Runtime.InteropServices;
namespace SampleBrightness
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct PHYSICAL_MONITOR
{
public IntPtr hPhysicalMonitor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
public string szPhysicalMonitorDescription;
}
public class BrightnessController : IDisposable
{
[DllImport("user32.dll", EntryPoint = "MonitorFromWindow")]
public static extern IntPtr MonitorFromWindow([In] IntPtr hwnd, uint dwFlags);
[DllImport("dxva2.dll", EntryPoint = "DestroyPhysicalMonitors")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DestroyPhysicalMonitors(uint dwPhysicalMonitorArraySize, ref PHYSICAL_MONITOR[] pPhysicalMonitorArray);
[DllImport("dxva2.dll", EntryPoint = "GetNumberOfPhysicalMonitorsFromHMONITOR")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(IntPtr hMonitor, ref uint pdwNumberOfPhysicalMonitors);
[DllImport("dxva2.dll", EntryPoint = "GetPhysicalMonitorsFromHMONITOR")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetPhysicalMonitorsFromHMONITOR(IntPtr hMonitor, uint dwPhysicalMonitorArraySize, [Out] PHYSICAL_MONITOR[] pPhysicalMonitorArray);
[DllImport("dxva2.dll", EntryPoint = "GetMonitorBrightness")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetMonitorBrightness(IntPtr handle, ref uint minimumBrightness, ref uint currentBrightness, ref uint maxBrightness);
[DllImport("dxva2.dll", EntryPoint = "SetMonitorBrightness")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetMonitorBrightness(IntPtr handle, uint newBrightness);
private uint _physicalMonitorsCount = 0;
private PHYSICAL_MONITOR[] _physicalMonitorArray;
private IntPtr _firstMonitorHandle;
private uint _minValue = 0;
private uint _maxValue = 0;
private uint _currentValue = 0;
public BrightnessController(IntPtr windowHandle)
{
uint dwFlags = 0u;
IntPtr ptr = MonitorFromWindow(windowHandle, dwFlags);
if (!GetNumberOfPhysicalMonitorsFromHMONITOR(ptr, ref _physicalMonitorsCount))
{
throw new Exception("Cannot get monitor count!");
}
_physicalMonitorArray = new PHYSICAL_MONITOR[_physicalMonitorsCount];
if (!GetPhysicalMonitorsFromHMONITOR(ptr, _physicalMonitorsCount, _physicalMonitorArray))
{
throw new Exception("Cannot get phisical monitor handle!");
}
_firstMonitorHandle = _physicalMonitorArray[0].hPhysicalMonitor;
if (!GetMonitorBrightness(_firstMonitorHandle, ref _minValue, ref _currentValue, ref _maxValue))
{
throw new Exception("Cannot get monitor brightness!");
}
}
public void SetBrightness(int newValue)
{
newValue = Math.Min(newValue, Math.Max(0, newValue));
_currentValue = (_maxValue - _minValue) * (uint)newValue / 100u + _minValue;
SetMonitorBrightness(_firstMonitorHandle, _currentValue);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (_physicalMonitorsCount > 0)
{
DestroyPhysicalMonitors(_physicalMonitorsCount, ref _physicalMonitorArray);
}
}
}
}
}
Hope this helps.

Using ShellExecuteEx in c# with Unicode Filename

I need to use ShellExecuteExin c#
my filename has unicode character when I pass filename to ShellExecuteEx it throws exception
cant find file
When function finisheed unicode character in filename change to '?'
[Serializable]
public struct ShellExecuteInfo
{
public int Size;
public uint Mask;
public IntPtr hwnd;
public string Verb;
public string File;
public string Parameters;
public string Directory;
public uint Show;
public IntPtr InstApp;
public IntPtr IDList;
public string Class;
public IntPtr hkeyClass;
public uint HotKey;
public IntPtr Icon;
public IntPtr Monitor;
}
// Code For OpenWithDialog Box
[DllImport("shell32.dll", SetLastError = true)]
extern public static bool
ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
public const uint SW_NORMAL = 1;
public static void OpenAs(string file)
{
ShellExecuteInfo sei = new ShellExecuteInfo();
sei.Size = Marshal.SizeOf(sei);
sei.Verb = "openas";
sei.File = file;
sei.Show = SW_NORMAL;
if (!ShellExecuteEx(ref sei))
throw new System.ComponentModel.Win32Exception();
}
The default character set is ANSI. So you need to specify the character set to be Unicode:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct ShellExecuteInfo
{
....
}
....
[DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool ShellExecuteEx(ref ShellExecuteInfo lpExecInfo);
Although personally, since this long struct is only ever passed by reference, and since you invariably use new to ensure initialization, I'd declare it as a class:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class ShellExecuteInfo
{
....
}
....
[DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
public static extern bool ShellExecuteEx(ShellExecuteInfo lpExecInfo);
Note that we removed the ref because a class is a reference type. As opposed to a struct which is a value type.
I would also comment that you got the field translation incorrect, at the icon/monitor union. A corrected translation would be:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public class ShellExecuteInfo
{
public int Size;
public uint Mask;
public IntPtr hwnd;
public string Verb;
public string File;
public string Parameters;
public string Directory;
public int Show;
public IntPtr InstApp;
public IntPtr IDList;
public string Class;
public IntPtr hkeyClass;
public uint HotKey;
public IntPtr IconOrMonitor;
public IntPtr Process;
}
Finally, for convenience, it is worth adding a constructor to the class to initialize the size field:
public ShellExecuteInfo()
{
Size = Marshal.SizeOf(this);
}
Of course, you can just use Process.Start for the code in the question:
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = true;
psi.Verb = "openas";
psi.FileName = file;
Process.Start(psi);
Opening a URL
Solution 1 - PInvoke without the nasty structure
[DllImport("shell32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern uint ShellExecute(IntPtr hwnd, string strOperation, string strFile, string strParameters, string strDirectory, Int32 nShowCmd);
string link = "http://www.yahoo.com";
string def = string.Empty;
IntPtr hWnd = (IntPtr)0;
uint ret = ShellExecute(hWnd, def, link, def, def, 0);
Solution 2: Use C# native
Process.Start(new ProcessStartInfo("cmd", "/c start " + link) { CreateNoWindow = true });
Solution 3: More C#
ProcessStartInfo URL = new ProcessStartInfo();
URL.FileName = link;
URL.CreateNoWindow = true;
URL.UseShellExecute = true;
Process.Start(URL);

SetupDiEnumDeviceInterfaces() always returns false - C# WPF

I am trying to connect to a USB device that is detected as a CDC device on my system using the following code :
(I have presented only the part of the code relevant to my problem)
The code compiles fine and SetupDiGetClassDevs function runs ok too.
But SetupDiEnumDeviceInterfaces always returns false and because of this I am not able to move any further. Please tell me where it is wrong. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Runtime.InteropServices;
using System.IO.Ports;
//**************************************************************
// Static class for access to USB dll for all the activity
// related to USB device
//**************************************************************
namespace USBDeviceConnect
{
#region Unmanaged
public class Native
{
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern IntPtr SetupDiGetClassDevs(
ref Guid ClassGuid,
IntPtr Enumerator,
IntPtr hwndParent,
UInt32 Flags);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern bool SetupDiEnumDeviceInterfaces(
IntPtr hDevInfo,
SP_DEVINFO_DATA devInfo,
ref Guid interfaceClassGuid,
UInt32 memberIndex,
ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport(#"setupapi.dll", CharSet = CharSet.Auto)]
public static extern Boolean SetupDiEnumDeviceInterfaces(
IntPtr hDevInfo,
IntPtr devInfo,
ref Guid interfaceClassGuid,
UInt32 memberIndex,
ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern int SetupDiDestroyDeviceInfoList(
IntPtr DeviceInfoSet);
[DllImport("setupapi.dll", CharSet = CharSet.Auto)]
public static extern bool SetupDiEnumDeviceInfo(
IntPtr DeviceInfoSet,
UInt32 MemberIndex,
ref SP_DEVINFO_DATA DeviceInfoData);
//SP_DEVINFO_DATA
[StructLayout(LayoutKind.Sequential)]
public struct SP_DEVINFO_DATA
{
public int cbSize;
public Guid ClassGuid;
public int DevInst;
public ulong Reserved;
}
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVICE_INTERFACE_DATA
{
public int cbSize;
public Guid interfaceClassGuid;
public int flags;
public ulong reserved;
};
//PARMS
public const int DIGCF_ALLCLASSES = (0x00000004);
public const int DIGCF_PRESENT = (0x00000002);
public const int DIGCF_PROFILE = (0x00000008);
public const int DIGCF_DEVICEINTERFACE = (0x00000010);
public const int INVALID_HANDLE_VALUE = -1;
public const int MAX_DEV_LEN = 1000;
public const int DEVICE_NOTIFY_WINDOW_HANDLE = (0x00000000);
public const int DEVICE_NOTIFY_SERVICE_HANDLE = (0x00000001);
public const int DEVICE_NOTIFY_ALL_INTERFACE_CLASSES = (0x00000004);
public const int DBT_DEVTYP_DEVICEINTERFACE = (0x00000005);
public const int DBT_DEVNODES_CHANGED = (0x0007);
public const int WM_DEVICECHANGE = (0x0219);
public const int DIF_PROPERTYCHANGE = (0x00000012);
public const int DICS_FLAG_GLOBAL = (0x00000001);
public const int DICS_FLAG_CONFIGSPECIFIC = (0x00000002);
public const int DICS_ENABLE = (0x00000001);
public const int DICS_DISABLE = (0x00000002);
public const long ERROR_NO_MORE_ITEMS = 259L;
public const int ERROR_SUCCESS = 0;
}
#endregion
/****************************************************************************/
static class AccessUSB
{
public static void Main()
{
ConnectToDevice();
}
/* Execution starts here */
public static void ConnectToDevice()
{
/* Get the info of all connected devices */
//Globally Unique Identifier (GUID) for CDC class devices.
Guid InterfaceClassGuid = new Guid("a5dcbf10653011d2901f00c04fb951ed");
IntPtr DeviceInfoTable = (IntPtr)Native.INVALID_HANDLE_VALUE;
Native.SP_DEVICE_INTERFACE_DATA InterfaceDataStructure = new Native.SP_DEVICE_INTERFACE_DATA();
Native.SP_DEVINFO_DATA DevInfoData = new Native.SP_DEVINFO_DATA();
uint InterfaceIndex = 0;
uint ErrorStatus;
StringBuilder DeviceName = new StringBuilder();
DeviceInfoTable = Native.SetupDiGetClassDevs(ref InterfaceClassGuid, IntPtr.Zero, IntPtr.Zero, Native.DIGCF_PRESENT | Native.DIGCF_DEVICEINTERFACE);
if (DeviceInfoTable.ToInt32() != Native.INVALID_HANDLE_VALUE)
{
//Initialize an appropriate SP_DEVINFO_DATA structure.
DevInfoData.cbSize = Marshal.SizeOf(DevInfoData);
while (true)
{
InterfaceDataStructure.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(InterfaceDataStructure);
bool bRslt = Native.SetupDiEnumDeviceInterfaces(DeviceInfoTable, IntPtr.Zero, ref InterfaceClassGuid, InterfaceIndex, ref InterfaceDataStructure);
if (bRslt == true)
{
ErrorStatus = (uint)System.Runtime.InteropServices.Marshal.GetLastWin32Error();
if (Native.ERROR_NO_MORE_ITEMS == ErrorStatus)
{
Native.SetupDiDestroyDeviceInfoList(DeviceInfoTable);//Clean up the old structure we no longer need.
return;
}
}
else //Else some other kind of unknown error ocurred...
{
ErrorStatus = (uint)System.Runtime.InteropServices.Marshal.GetLastWin32Error();
Native.SetupDiDestroyDeviceInfoList(DeviceInfoTable); //Clean up the old structure we no longer need.
return;
}
InterfaceIndex++;
}//end of while(true)
}
}
}
}
I'm not sure why you are trying to use SetupAPI. If it is a detected as a CDC ACM device, then it should have the usbser.sys driver associated with it, and it should show a COM port number in the Device Manager, and you can connect to that COM port using the .NET SerialPort class:
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

How to access to SysListView32 Services Tab in Windows taskmanager

I'm trying to recover some items from Windows taskmanager.
With this code i recovered the SysListView32 handle from Process TAB:
(dlgItem)
IntPtr mainWindowHandle = Process.GetProcessesByName("taskmgr")[0].MainWindowHandle;
Api.WindowPlacement lpwndpl = new Api.WindowPlacement();
lpwndpl.length = Marshal.SizeOf((object) lpwndpl);
Api.GetWindowPlacement(mainWindowHandle, ref lpwndpl);
bool flag1 = lpwndpl.showCmd == 1 || lpwndpl.showCmd == 3;
IntPtr dlgItem = Api.GetDlgItem(Api.FindWindowEx(mainWindowHandle, IntPtr.Zero, (string) null, (string) null), 1009);
How can i recover the handle for SysListView32 Services TAB?
Some API definitions im using:
internal static class Api
{
public struct Rect
{
private int left;
private int top;
private int right;
private int bottom;
}
public struct Point
{
private int x;
private int y;
}
public struct WindowPlacement
{
public int length;
public int flags;
public int showCmd;
public Api.Point ptMinPosition;
public Api.Point ptMaxPosition;
public Api.Rect rcNormalPosition;
}
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetWindowPlacement(IntPtr hWnd, ref Api.WindowPlacement lpwndpl);
[DllImport("user32.dll")]
public static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", SetLastError = true)]
public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);
}
You must use FindWindowEx with a class name (lpszClass) equal to "#32770" and a Window Title (lpszWindow) equal to "Services". The ID of the child SysListView32 is then 3504 (0x0000db0).
Those datas come from Spy++, used on a French Windows Seven Pro 32bits OS.

HDMI TV sometimes not detected in windows 7? Possible to invoke Detect in code?

i have a standalone public kiosk pc that startups automatically everyday. It is connected to a HD TV and sometimes it is not detected. i have to personally go down to the PC, go to Screen Resolution and press Detect which it works.
my question is how do i know if the monitor i want it to display is connected properly in code?
thanks
I did manage to find some code on the MSDN site where a user is using code to determine which type of monitor is connected. I hope this may be a good starting point for you.
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Interop;
namespace CRT
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public class NativeMethods
{
[DllImport("user32.dll", EntryPoint = "MonitorFromWindow", SetLastError = true)]
public static extern IntPtr MonitorFromWindow(
[In] IntPtr hwnd, uint dwFlags);
[DllImport("dxva2.dll", EntryPoint = "GetNumberOfPhysicalMonitorsFromHMONITOR", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetNumberOfPhysicalMonitorsFromHMONITOR(
IntPtr hMonitor, ref uint pdwNumberOfPhysicalMonitors);
[DllImport("dxva2.dll", EntryPoint = "GetPhysicalMonitorsFromHMONITOR", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetPhysicalMonitorsFromHMONITOR(
IntPtr hMonitor,
uint dwPhysicalMonitorArraySize,
[Out] NativeStructures.PHYSICAL_MONITOR[] pPhysicalMonitorArray);
[DllImport("dxva2.dll", EntryPoint = "DestroyPhysicalMonitors", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool DestroyPhysicalMonitors(
uint dwPhysicalMonitorArraySize, [Out] NativeStructures.PHYSICAL_MONITOR[] pPhysicalMonitorArray);
[DllImport("dxva2.dll", EntryPoint = "GetMonitorTechnologyType", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetMonitorTechnologyType(
IntPtr hMonitor, ref NativeStructures.MC_DISPLAY_TECHNOLOGY_TYPE pdtyDisplayTechnologyType);
[DllImport("dxva2.dll", EntryPoint = "GetMonitorCapabilities", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool GetMonitorCapabilities(
IntPtr hMonitor, ref uint pdwMonitorCapabilities, ref uint pdwSupportedColorTemperatures);
}
public class NativeConstants
{
public const int MONITOR_DEFAULTTOPRIMARY = 1;
public const int MONITOR_DEFAULTTONEAREST = 2;
public const int MONITOR_DEFAULTTONULL = 0;
}
public class NativeStructures
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct PHYSICAL_MONITOR
{
public IntPtr hPhysicalMonitor;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)] public string szPhysicalMonitorDescription;
}
public enum MC_DISPLAY_TECHNOLOGY_TYPE
{
MC_SHADOW_MASK_CATHODE_RAY_TUBE,
MC_APERTURE_GRILL_CATHODE_RAY_TUBE,
MC_THIN_FILM_TRANSISTOR,
MC_LIQUID_CRYSTAL_ON_SILICON,
MC_PLASMA,
MC_ORGANIC_LIGHT_EMITTING_DIODE,
MC_ELECTROLUMINESCENT,
MC_MICROELECTROMECHANICAL,
MC_FIELD_EMISSION_DEVICE,
}
}
public Window1() { InitializeComponent(); }
private void Button_Click(object sender, RoutedEventArgs e)
{
WindowInteropHelper helper = new WindowInteropHelper(this);
IntPtr hMonitor = NativeMethods.MonitorFromWindow(helper.Handle, NativeConstants.MONITOR_DEFAULTTOPRIMARY);
int lastWin32Error = Marshal.GetLastWin32Error();
uint pdwNumberOfPhysicalMonitors = 0u;
bool numberOfPhysicalMonitorsFromHmonitor = NativeMethods.GetNumberOfPhysicalMonitorsFromHMONITOR(
hMonitor, ref pdwNumberOfPhysicalMonitors);
lastWin32Error = Marshal.GetLastWin32Error();
NativeStructures.PHYSICAL_MONITOR[] pPhysicalMonitorArray =
new NativeStructures.PHYSICAL_MONITOR[pdwNumberOfPhysicalMonitors];
bool physicalMonitorsFromHmonitor = NativeMethods.GetPhysicalMonitorsFromHMONITOR(
hMonitor, pdwNumberOfPhysicalMonitors, pPhysicalMonitorArray);
lastWin32Error = Marshal.GetLastWin32Error();
uint pdwMonitorCapabilities = 0u;
uint pdwSupportedColorTemperatures = 0u;
var monitorCapabilities = NativeMethods.GetMonitorCapabilities(
pPhysicalMonitorArray[0].hPhysicalMonitor, ref pdwMonitorCapabilities, ref pdwSupportedColorTemperatures);
lastWin32Error = Marshal.GetLastWin32Error();
NativeStructures.MC_DISPLAY_TECHNOLOGY_TYPE type =
NativeStructures.MC_DISPLAY_TECHNOLOGY_TYPE.MC_SHADOW_MASK_CATHODE_RAY_TUBE;
var monitorTechnologyType = NativeMethods.GetMonitorTechnologyType(
pPhysicalMonitorArray[0].hPhysicalMonitor, ref type);
lastWin32Error = Marshal.GetLastWin32Error();
var destroyPhysicalMonitors = NativeMethods.DestroyPhysicalMonitors(
pdwNumberOfPhysicalMonitors, pPhysicalMonitorArray);
lastWin32Error = Marshal.GetLastWin32Error();
this.lbl.Content = type;
}
}
}

Categories