зеркало из
1
0
Форкнуть 0

[WindowsPlatform] Initial binary replacement with sources.

This commit is contained in:
Marius Ungureanu 2014-03-19 15:31:15 +02:00
Коммит 2ab351ddab
240 изменённых файлов: 73233 добавлений и 0 удалений

Просмотреть файл

@ -0,0 +1,56 @@
using System;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// This exception is thrown when there are problems with registering, unregistering or updating
/// applications using Application Restart Recovery.
/// </summary>
[Serializable]
public class ApplicationRecoveryException : ExternalException
{
/// <summary>
/// Default constructor.
/// </summary>
public ApplicationRecoveryException() { }
/// <summary>
/// Initializes an exception with a custom message.
/// </summary>
/// <param name="message">A custom message for the exception.</param>
public ApplicationRecoveryException(string message) : base(message) { }
/// <summary>
/// Initializes an exception with custom message and inner exception.
/// </summary>
/// <param name="message">A custom message for the exception.</param>
/// <param name="innerException">Inner exception.</param>
public ApplicationRecoveryException(string message, Exception innerException)
: base(message, innerException)
{
// Empty
}
/// <summary>
/// Initializes an exception with custom message and error code.
/// </summary>
/// <param name="message">A custom message for the exception.</param>
/// <param name="errorCode">An error code (hresult) from which to generate the exception.</param>
public ApplicationRecoveryException(string message, int errorCode) : base(message, errorCode) { }
/// <summary>
/// Initializes an exception from serialization info and a context.
/// </summary>
/// <param name="info">Serialization info from which to create exception.</param>
/// <param name="context">Streaming context from which to create exception.</param>
protected ApplicationRecoveryException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
// Empty
}
}
}

Просмотреть файл

@ -0,0 +1,163 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Resources;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Provides access to the Application Restart and Recovery
/// features available in Windows Vista or higher. Application Restart and Recovery lets an
/// application do some recovery work to save data before the process exits.
/// </summary>
public static class ApplicationRestartRecoveryManager
{
/// <summary>
/// Registers an application for recovery by Application Restart and Recovery.
/// </summary>
/// <param name="settings">An object that specifies
/// the callback method, an optional parameter to pass to the callback
/// method and a time interval.</param>
/// <exception cref="System.ArgumentException">
/// The registration failed due to an invalid parameter.
/// </exception>
/// <exception cref="System.ComponentModel.Win32Exception">
/// The registration failed.</exception>
/// <remarks>The time interval is the period of time within
/// which the recovery callback method
/// calls the <see cref="ApplicationRecoveryInProgress"/> method to indicate
/// that it is still performing recovery work.</remarks>
public static void RegisterForApplicationRecovery(RecoverySettings settings)
{
CoreHelpers.ThrowIfNotVista();
if (settings == null) { throw new ArgumentNullException("settings"); }
GCHandle handle = GCHandle.Alloc(settings.RecoveryData);
HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRecoveryCallback(
AppRestartRecoveryNativeMethods.InternalCallback, (IntPtr)handle, settings.PingInterval, (uint)0);
if (!CoreErrorHelper.Succeeded(hr))
{
if (hr == HResult.InvalidArguments)
{
throw new ArgumentException(LocalizedMessages.ApplicationRecoveryBadParameters, "settings");
}
throw new ApplicationRecoveryException(LocalizedMessages.ApplicationRecoveryFailedToRegister);
}
}
/// <summary>
/// Removes an application's recovery registration.
/// </summary>
/// <exception cref="Microsoft.WindowsAPICodePack.ApplicationServices.ApplicationRecoveryException">
/// The attempt to unregister for recovery failed.</exception>
public static void UnregisterApplicationRecovery()
{
CoreHelpers.ThrowIfNotVista();
HResult hr = AppRestartRecoveryNativeMethods.UnregisterApplicationRecoveryCallback();
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ApplicationRecoveryException(LocalizedMessages.ApplicationRecoveryFailedToUnregister);
}
}
/// <summary>
/// Removes an application's restart registration.
/// </summary>
/// <exception cref="Microsoft.WindowsAPICodePack.ApplicationServices.ApplicationRecoveryException">
/// The attempt to unregister for restart failed.</exception>
public static void UnregisterApplicationRestart()
{
CoreHelpers.ThrowIfNotVista();
HResult hr = AppRestartRecoveryNativeMethods.UnregisterApplicationRestart();
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ApplicationRecoveryException(LocalizedMessages.ApplicationRecoveryFailedToUnregisterForRestart);
}
}
/// <summary>
/// Called by an application's <see cref="RecoveryCallback"/> method
/// to indicate that it is still performing recovery work.
/// </summary>
/// <returns>A <see cref="System.Boolean"/> value indicating whether the user
/// canceled the recovery.</returns>
/// <exception cref="Microsoft.WindowsAPICodePack.ApplicationServices.ApplicationRecoveryException">
/// This method must be called from a registered callback method.</exception>
public static bool ApplicationRecoveryInProgress()
{
CoreHelpers.ThrowIfNotVista();
bool canceled = false;
HResult hr = AppRestartRecoveryNativeMethods.ApplicationRecoveryInProgress(out canceled);
if (!CoreErrorHelper.Succeeded(hr))
{
throw new InvalidOperationException(LocalizedMessages.ApplicationRecoveryMustBeCalledFromCallback);
}
return canceled;
}
/// <summary>
/// Called by an application's <see cref="RecoveryCallback"/> method to
/// indicate that the recovery work is complete.
/// </summary>
/// <remarks>
/// This should
/// be the last call made by the <see cref="RecoveryCallback"/> method because
/// Windows Error Reporting will terminate the application
/// after this method is invoked.
/// </remarks>
/// <param name="success"><b>true</b> to indicate the the program was able to complete its recovery
/// work before terminating; otherwise <b>false</b>.</param>
public static void ApplicationRecoveryFinished(bool success)
{
CoreHelpers.ThrowIfNotVista();
AppRestartRecoveryNativeMethods.ApplicationRecoveryFinished(success);
}
/// <summary>
/// Registers an application for automatic restart if
/// the application
/// is terminated by Windows Error Reporting.
/// </summary>
/// <param name="settings">An object that specifies
/// the command line arguments used to restart the
/// application, and
/// the conditions under which the application should not be
/// restarted.</param>
/// <exception cref="System.ArgumentException">Registration failed due to an invalid parameter.</exception>
/// <exception cref="System.InvalidOperationException">The attempt to register failed.</exception>
/// <remarks>A registered application will not be restarted if it executed for less than 60 seconds before terminating.</remarks>
public static void RegisterForApplicationRestart(RestartSettings settings)
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
if (settings == null) { throw new ArgumentNullException("settings"); }
HResult hr = AppRestartRecoveryNativeMethods.RegisterApplicationRestart(settings.Command, settings.Restrictions);
if (hr == HResult.Fail)
{
throw new InvalidOperationException(LocalizedMessages.ApplicationRecoveryFailedToRegisterForRestart);
}
else if (hr == HResult.InvalidArguments)
{
throw new ArgumentException(LocalizedMessages.ApplicationRecoverFailedToRegisterForRestartBadParameters);
}
}
}
}

Просмотреть файл

@ -0,0 +1,54 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// The <see cref="System.Delegate"/> that represents the callback method invoked
/// by the system when an application has registered for
/// application recovery.
/// </summary>
/// <param name="state">An application-defined state object that is passed to the callback method.</param>
/// <remarks>The callback method will be invoked
/// prior to the application being terminated by Windows Error Reporting (WER). To keep WER from terminating the application before
/// the callback method completes, the callback method must
/// periodically call the <see cref="ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress"/> method. </remarks>
/// <seealso cref="ApplicationRestartRecoveryManager.RegisterForApplicationRecovery(RecoverySettings)"/>
public delegate int RecoveryCallback(object state);
/// <summary>
/// Defines a class that contains a callback delegate and properties of the application
/// as defined by the user.
/// </summary>
public class RecoveryData
{
/// <summary>
/// Initializes a recovery data wrapper with a callback method and the current
/// state of the application.
/// </summary>
/// <param name="callback">The callback delegate.</param>
/// <param name="state">The current state of the application.</param>
public RecoveryData(RecoveryCallback callback, object state)
{
Callback = callback;
State = state;
}
/// <summary>
/// Gets or sets a value that determines the recovery callback function.
/// </summary>
public RecoveryCallback Callback { get; set; }
/// <summary>
/// Gets or sets a value that determines the application state.
/// </summary>
public object State { get; set; }
/// <summary>
/// Invokes the recovery callback function.
/// </summary>
public void Invoke()
{
if (Callback != null) { Callback(State); }
}
}
}

Просмотреть файл

@ -0,0 +1,74 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Defines methods and properties for recovery settings, and specifies options for an application that attempts
/// to perform final actions after a fatal event, such as an
/// unhandled exception.
/// </summary>
/// <remarks>This class is used to register for application recovery.
/// See the <see cref="ApplicationRestartRecoveryManager"/> class.
/// </remarks>
public class RecoverySettings
{
private RecoveryData recoveryData;
private uint pingInterval;
/// <summary>
/// Initializes a new instance of the <b>RecoverySettings</b> class.
/// </summary>
/// <param name="data">A recovery data object that contains the callback method (invoked by the system
/// before Windows Error Reporting terminates the application) and an optional state object.</param>
/// <param name="interval">The time interval within which the
/// callback method must invoke <see cref="ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress"/> to
/// prevent WER from terminating the application.</param>
/// <seealso cref="ApplicationRestartRecoveryManager"/>
public RecoverySettings(RecoveryData data, uint interval)
{
this.recoveryData = data;
this.pingInterval = interval;
}
/// <summary>
/// Gets the recovery data object that contains the callback method and an optional
/// parameter (usually the state of the application) to be passed to the
/// callback method.
/// </summary>
/// <value>A <see cref="RecoveryData"/> object.</value>
public RecoveryData RecoveryData
{
get { return recoveryData; }
}
/// <summary>
/// Gets the time interval for notifying Windows Error Reporting.
/// The <see cref="RecoveryCallback"/> method must invoke <see cref="ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress"/>
/// within this interval to prevent WER from terminating the application.
/// </summary>
/// <remarks>
/// The recovery ping interval is specified in milliseconds.
/// By default, the interval is 5 seconds.
/// If you specify zero, the default interval is used.
/// </remarks>
public uint PingInterval { get { return pingInterval; } }
/// <summary>
/// Returns a string representation of the current state
/// of this object.
/// </summary>
/// <returns>A <see cref="System.String"/> object.</returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.RecoverySettingsFormatString,
this.recoveryData.Callback.Method.ToString(),
this.recoveryData.State.ToString(),
this.PingInterval);
}
}
}

Просмотреть файл

@ -0,0 +1,38 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Specifies the conditions when Windows Error Reporting
/// should not restart an application that has registered
/// for automatic restart.
/// </summary>
[Flags]
public enum RestartRestrictions
{
/// <summary>
/// Always restart the application.
/// </summary>
None = 0,
/// <summary>
/// Do not restart when the application has crashed.
/// </summary>
NotOnCrash = 1,
/// <summary>
/// Do not restart when the application is hung.
/// </summary>
NotOnHang = 2,
/// <summary>
/// Do not restart when the application is terminated
/// due to a system update.
/// </summary>
NotOnPatch = 4,
/// <summary>
/// Do not restart when the application is terminated
/// because of a system reboot.
/// </summary>
NotOnReboot = 8
}
}

Просмотреть файл

@ -0,0 +1,70 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Specifies the options for an application to be automatically
/// restarted by Windows Error Reporting.
/// </summary>
/// <remarks>Regardless of these
/// settings, the application
/// will not be restarted if it executed for less than 60 seconds before
/// terminating.</remarks>
public class RestartSettings
{
private string command;
private RestartRestrictions restrictions;
/// <summary>
/// Creates a new instance of the RestartSettings class.
/// </summary>
/// <param name="command">The command line arguments
/// used to restart the application.</param>
/// <param name="restrictions">A bitwise combination of the RestartRestrictions
/// values that specify
/// when the application should not be restarted.
/// </param>
public RestartSettings(string command, RestartRestrictions restrictions)
{
this.command = command;
this.restrictions = restrictions;
}
/// <summary>
/// Gets the command line arguments used to restart the application.
/// </summary>
/// <value>A <see cref="System.String"/> object.</value>
public string Command
{
get { return command; }
}
/// <summary>
/// Gets the set of conditions when the application
/// should not be restarted.
/// </summary>
/// <value>A set of <see cref="RestartRestrictions"/> values.</value>
public RestartRestrictions Restrictions
{
get { return restrictions; }
}
/// <summary>
/// Returns a string representation of the current state
/// of this object.
/// </summary>
/// <returns>A <see cref="System.String"/> that displays
/// the command line arguments
/// and restrictions for restarting the application.</returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.RestartSettingsFormatString,
command, restrictions.ToString());
}
}
}

217
Core/Core.csproj Normal file
Просмотреть файл

@ -0,0 +1,217 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{2E1FB0DF-F9BB-4909-9F32-2D9D022A8E57}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Microsoft.WindowsAPICodePack</RootNamespace>
<AssemblyName>Microsoft.WindowsAPICodePack</AssemblyName>
<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<FileUpgradeFlags>
</FileUpgradeFlags>
<OldToolsVersion>3.5</OldToolsVersion>
<UpgradeBackupLocation />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<DocumentationFile>bin\Debug\Microsoft.WindowsAPICodePack.XML</DocumentationFile>
<CodeAnalysisRules>
</CodeAnalysisRules>
<RunCodeAnalysis>false</RunCodeAnalysis>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>CODE_ANALYSIS;DEBUG;TRACE</DefineConstants>
<DocumentationFile>bin\Debug\Microsoft.WindowsAPICodePack.XML</DocumentationFile>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<CodeAnalysisLogFile>bin\Debug\Microsoft.WindowsAPICodePack.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<RunCodeAnalysis>false</RunCodeAnalysis>
<WarningLevel>4</WarningLevel>
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<CodeAnalysisLogFile>bin\Release\Microsoft.WindowsAPICodePack.dll.CodeAnalysisLog.xml</CodeAnalysisLogFile>
<CodeAnalysisUseTypeNameInSuppression>true</CodeAnalysisUseTypeNameInSuppression>
<CodeAnalysisModuleSuppressionsFile>GlobalSuppressions.cs</CodeAnalysisModuleSuppressionsFile>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>AllRules.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisRuleSetDirectories>;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\\Rule Sets</CodeAnalysisRuleSetDirectories>
<CodeAnalysisIgnoreBuiltInRuleSets>true</CodeAnalysisIgnoreBuiltInRuleSets>
<CodeAnalysisRuleDirectories>;c:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Static Analysis Tools\FxCop\\Rules</CodeAnalysisRuleDirectories>
<CodeAnalysisIgnoreBuiltInRules>true</CodeAnalysisIgnoreBuiltInRules>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core">
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Data" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="AppRestartRecovery\ApplicationRestartRecoveryManager.cs" />
<Compile Include="AppRestartRecovery\ApplicationRecoveryException.cs" />
<Compile Include="AppRestartRecovery\RecoveryData.cs" />
<Compile Include="AppRestartRecovery\RecoverySettings.cs" />
<Compile Include="AppRestartRecovery\RestartRestrictions.cs" />
<Compile Include="AppRestartRecovery\RestartSettings.cs" />
<Compile Include="Interop\WindowMessage.cs" />
<Compile Include="PowerManagement\PowerManagerException.cs" />
<Compile Include="Dialogs\Common\DialogControl.cs" />
<Compile Include="Dialogs\Common\DialogControlCollection.cs" />
<Compile Include="Dialogs\Common\DialogsDefaults.cs" />
<Compile Include="Dialogs\Common\IDialogControlHost.cs" />
<Compile Include="GlobalSuppressions.cs" />
<Compile Include="Interop\AppRestartRecovery\AppRestartRecoveryNativeMethods.cs" />
<Compile Include="Interop\CoreErrorHelper.cs" />
<Compile Include="Interop\CoreHelpers.cs" />
<Compile Include="Interop\CoreNativeMethods.cs" />
<Compile Include="Interop\Dialogs\DialogShowState.cs" />
<Compile Include="Interop\NetworkList\INetwork.cs" />
<Compile Include="Interop\NetworkList\INetworkConnection.cs" />
<Compile Include="Interop\NetworkList\INetworkListManager.cs" />
<Compile Include="Interop\NetworkList\NetworkListManagerClass.cs" />
<Compile Include="Interop\PowerManagement\PowerManagementNativeMethods.cs" />
<Compile Include="Interop\TaskDialogs\NativeTaskDialog.cs" />
<Compile Include="Interop\TaskDialogs\NativeTaskDialogSettings.cs" />
<Compile Include="Interop\TaskDialogs\TaskDialogNativeMethods.cs" />
<Compile Include="NetworkList\Network.cs" />
<Compile Include="NetworkList\NetworkCollection.cs" />
<Compile Include="NetworkList\NetworkConnection.cs" />
<Compile Include="NetworkList\NetworkConnectionCollection.cs" />
<Compile Include="NetworkList\NetworkListEnums.cs" />
<Compile Include="NetworkList\NetworkListManager.cs" />
<Compile Include="PowerManagement\BatteryState.cs" />
<Compile Include="PowerManagement\EventManager.cs" />
<Compile Include="PowerManagement\ExecutionState.cs" />
<Compile Include="PowerManagement\MessageManager.cs">
</Compile>
<Compile Include="PowerManagement\PersonalityGuids.cs" />
<Compile Include="PowerManagement\Power.cs" />
<Compile Include="PowerManagement\PowerManager.cs" />
<Compile Include="PowerManagement\PowerPersonality.cs" />
<Compile Include="PowerManagement\PowerSource.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="PropertySystem\PropertyKey.cs" />
<Compile Include="PropertySystem\PropVariant.cs" />
<Compile Include="PropertySystem\PropVariantNativeMethods.cs" />
<Compile Include="Resources\LocalizedMessages.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>LocalizedMessages.resx</DependentUpon>
</Compile>
<Compile Include="SafeHandles\ZeroInvalidHandle.cs" />
<Compile Include="SafeHandles\SafeIconHandle.cs" />
<Compile Include="SafeHandles\SafeRegionHandle.cs" />
<Compile Include="SafeHandles\SafeWindowHandle.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialog.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogBar.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogButton.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogButtonBase.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogClosingEventArgs.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogCommandLink.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogControl.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogDefaults.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogExpandedInfoMode.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogHyperlinkClickedEventArgs.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogProgressBar.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogProgressBarState.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogRadioButton.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogResult.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogStandardButton.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogStandardIcon.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogStartupLocation.cs" />
<Compile Include="Dialogs\TaskDialogs\TaskDialogTickEventArgs.cs" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include="Microsoft.Net.Client.3.5">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
<Install>false</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Windows.Installer.3.1">
<Visible>False</Visible>
<ProductName>Windows Installer 3.1</ProductName>
<Install>true</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Resources\LocalizedMessages.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>LocalizedMessages.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<CodeAnalysisDictionary Include="CustomDictionary.xml">
<SubType>Designer</SubType>
</CodeAnalysisDictionary>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

16
Core/CustomDictionary.xml Normal file
Просмотреть файл

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8" ?>
<Dictionary>
<Words>
<Recognized>
<Word>IPv4</Word>
<Word>IPv6</Word>
<Word>comctl</Word>
<Word>Wh</Word>
</Recognized>
</Words>
<Acronyms>
<CasingExceptions>
<Acronym>API</Acronym>
</CasingExceptions>
</Acronyms>
</Dictionary>

Просмотреть файл

@ -0,0 +1,147 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Diagnostics;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Abstract base class for all dialog controls
/// </summary>
public abstract class DialogControl
{
private static int nextId = DialogsDefaults.MinimumDialogControlId;
/// <summary>
/// Creates a new instance of a dialog control
/// </summary>
protected DialogControl()
{
Id = nextId;
// Support wrapping of control IDs in case you create a lot of custom controls
if (nextId == Int32.MaxValue) { nextId = DialogsDefaults.MinimumDialogControlId; }
else { nextId++; }
}
/// <summary>
/// Creates a new instance of a dialog control with the specified name.
/// </summary>
/// <param name="name">The name for this dialog.</param>
protected DialogControl(string name)
: this()
{
Name = name;
}
/// <summary>
/// The native dialog that is hosting this control. This property is null is
/// there is not associated dialog
/// </summary>
public IDialogControlHost HostingDialog { get; set; }
private string name;
/// <summary>
/// Gets the name for this control.
/// </summary>
/// <value>A <see cref="System.String"/> value.</value>
public string Name
{
get { return name; }
set
{
// Names for controls need to be quite stable,
// as we are going to maintain a mapping between
// the names and the underlying Win32/COM control IDs.
if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(LocalizedMessages.DialogControlNameCannotBeEmpty);
}
if (!string.IsNullOrEmpty(name))
{
throw new InvalidOperationException(LocalizedMessages.DialogControlsCannotBeRenamed);
}
// Note that we don't notify the hosting dialog of
// the change, as the initial set of name is (must be)
// always legal, and renames are always illegal.
this.name = value;
}
}
/// <summary>
/// Gets the identifier for this control.
/// </summary>
/// <value>An <see cref="System.Int32"/> value.</value>
public int Id { get; private set; }
///<summary>
/// Calls the hosting dialog, if it exists, to check whether the
/// property can be set in the dialog's current state.
/// The host should throw an exception if the change is not supported.
/// Note that if the dialog isn't set yet,
/// there are no restrictions on setting the property.
/// </summary>
/// <param name="propName">The name of the property that is changing</param>
protected void CheckPropertyChangeAllowed(string propName)
{
Debug.Assert(!string.IsNullOrEmpty(propName), "Property to change was not specified");
if (HostingDialog != null)
{
// This will throw if the property change is not allowed.
HostingDialog.IsControlPropertyChangeAllowed(propName, this);
}
}
///<summary>
/// Calls the hosting dialog, if it exists, to
/// to indicate that a property has changed, and that
/// the dialog should do whatever is necessary
/// to propagate the change to the native control.
/// Note that if the dialog isn't set yet,
/// there are no restrictions on setting the property.
/// </summary>
/// <param name="propName">The name of the property that is changing.</param>
protected void ApplyPropertyChange(string propName)
{
Debug.Assert(!string.IsNullOrEmpty(propName), "Property changed was not specified");
if (HostingDialog != null)
{
HostingDialog.ApplyControlPropertyChange(propName, this);
}
}
/// <summary>
/// Compares two objects to determine whether they are equal
/// </summary>
/// <param name="obj">The object to compare against.</param>
/// <returns>A <see cref="System.Boolean"/> value.</returns>
public override bool Equals(object obj)
{
DialogControl control = obj as DialogControl;
if (control != null)
return (this.Id == control.Id);
return false;
}
/// <summary>
/// Serves as a hash function for a particular type.
/// </summary>
/// <returns>An <see cref="System.Int32"/> hash code for this control.</returns>
public override int GetHashCode()
{
if (Name == null)
{
return this.ToString().GetHashCode();
}
return Name.GetHashCode();
}
}
}

Просмотреть файл

@ -0,0 +1,120 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.ObjectModel;
using System.Linq;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Strongly typed collection for dialog controls.
/// </summary>
/// <typeparam name="T">DialogControl</typeparam>
public sealed class DialogControlCollection<T> : Collection<T> where T : DialogControl
{
private IDialogControlHost hostingDialog;
internal DialogControlCollection(IDialogControlHost host)
{
hostingDialog = host;
}
/// <summary>
/// Inserts an dialog control at the specified index.
/// </summary>
/// <param name="index">The location to insert the control.</param>
/// <param name="control">The item to insert.</param>
/// <permission cref="System.InvalidOperationException">A control with
/// the same name already exists in this collection -or-
/// the control is being hosted by another dialog -or- the associated dialog is
/// showing and cannot be modified.</permission>
protected override void InsertItem(int index, T control)
{
// Check for duplicates, lack of host,
// and during-show adds.
if (Items.Contains(control))
{
throw new InvalidOperationException(LocalizedMessages.DialogCollectionCannotHaveDuplicateNames);
}
if (control.HostingDialog != null)
{
throw new InvalidOperationException(LocalizedMessages.DialogCollectionControlAlreadyHosted);
}
if (!hostingDialog.IsCollectionChangeAllowed())
{
throw new InvalidOperationException(LocalizedMessages.DialogCollectionModifyShowingDialog);
}
// Reparent, add control.
control.HostingDialog = hostingDialog;
base.InsertItem(index, control);
// Notify that we've added a control.
hostingDialog.ApplyCollectionChanged();
}
/// <summary>
/// Removes the control at the specified index.
/// </summary>
/// <param name="index">The location of the control to remove.</param>
/// <permission cref="System.InvalidOperationException">
/// The associated dialog is
/// showing and cannot be modified.</permission>
protected override void RemoveItem(int index)
{
// Notify that we're about to remove a control.
// Throw if dialog showing.
if (!hostingDialog.IsCollectionChangeAllowed())
{
throw new InvalidOperationException(LocalizedMessages.DialogCollectionModifyShowingDialog);
}
DialogControl control = (DialogControl)Items[index];
// Unparent and remove.
control.HostingDialog = null;
base.RemoveItem(index);
hostingDialog.ApplyCollectionChanged();
}
/// <summary>
/// Defines the indexer that supports accessing controls by name.
/// </summary>
/// <remarks>
/// <para>Control names are case sensitive.</para>
/// <para>This indexer is useful when the dialog is created in XAML
/// rather than constructed in code.</para></remarks>
///<exception cref="System.ArgumentException">
/// The name cannot be null or a zero-length string.</exception>
/// <remarks>If there is more than one control with the same name, only the <B>first control</B> will be returned.</remarks>
public T this[string name]
{
get
{
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException(LocalizedMessages.DialogCollectionControlNameNull, "name");
}
return Items.FirstOrDefault(x => x.Name == name);
}
}
/// <summary>
/// Searches for the control who's id matches the value
/// passed in the <paramref name="id"/> parameter.
/// </summary>
///
/// <param name="id">An integer containing the identifier of the
/// control being searched for.</param>
///
/// <returns>A DialogControl who's id matches the value of the
/// <paramref name="id"/> parameter.</returns>
internal DialogControl GetControlbyId(int id)
{
return Items.FirstOrDefault(x => x.Id == id);
}
}
}

Просмотреть файл

@ -0,0 +1,23 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
internal static class DialogsDefaults
{
internal static string Caption { get { return LocalizedMessages.DialogDefaultCaption; } }
internal static string MainInstruction { get { return LocalizedMessages.DialogDefaultMainInstruction; } }
internal static string Content { get { return LocalizedMessages.DialogDefaultContent; } }
internal const int ProgressBarStartingValue = 0;
internal const int ProgressBarMinimumValue = 0;
internal const int ProgressBarMaximumValue = 100;
internal const int IdealWidth = 0;
// For generating control ID numbers that won't
// collide with the standard button return IDs.
internal const int MinimumDialogControlId =
(int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close + 1;
}
}

Просмотреть файл

@ -0,0 +1,43 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Indicates that the implementing class is a dialog that can host
/// customizable dialog controls (subclasses of DialogControl).
/// </summary>
public interface IDialogControlHost
{
/// <summary>
/// Returns if changes to the collection are allowed.
/// </summary>
/// <returns>true if collection change is allowed.</returns>
bool IsCollectionChangeAllowed();
/// <summary>
/// Applies changes to the collection.
/// </summary>
void ApplyCollectionChanged();
/// <summary>
/// Handle notifications of individual child
/// pseudo-controls' properties changing..
/// Prefilter should throw if the property
/// cannot be set in the dialog's current state.
/// PostProcess should pass on changes to native control,
/// if appropriate.
/// </summary>
/// <param name="propertyName">The name of the property.</param>
/// <param name="control">The control propertyName applies to.</param>
/// <returns>true if the property change is allowed.</returns>
bool IsControlPropertyChangeAllowed(string propertyName, DialogControl control);
/// <summary>
/// Called when a control currently in the collection
/// has a property changed.
/// </summary>
/// <param name="propertyName">The name of the property changed.</param>
/// <param name="control">The control whose property has changed.</param>
void ApplyControlPropertyChange(string propertyName, DialogControl control);
}
}

Разница между файлами не показана из-за своего большого размера Загрузить разницу

Просмотреть файл

@ -0,0 +1,43 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Defines a common class for all task dialog bar controls, such as the progress and marquee bars.
/// </summary>
public class TaskDialogBar : TaskDialogControl
{
/// <summary>
/// Creates a new instance of this class.
/// </summary>
public TaskDialogBar() { }
/// <summary>
/// Creates a new instance of this class with the specified name.
/// </summary>
/// <param name="name">The name for this control.</param>
protected TaskDialogBar(string name) : base(name) { }
private TaskDialogProgressBarState state;
/// <summary>
/// Gets or sets the state of the progress bar.
/// </summary>
public TaskDialogProgressBarState State
{
get { return state; }
set
{
CheckPropertyChangeAllowed("State");
state = value;
ApplyPropertyChange("State");
}
}
/// <summary>
/// Resets the state of the control to normal.
/// </summary>
protected internal virtual void Reset()
{
state = TaskDialogProgressBarState.Normal;
}
}
}

Просмотреть файл

@ -0,0 +1,37 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Implements a button that can be hosted in a task dialog.
/// </summary>
public class TaskDialogButton : TaskDialogButtonBase
{
/// <summary>
/// Creates a new instance of this class.
/// </summary>
public TaskDialogButton() { }
/// <summary>
/// Creates a new instance of this class with the specified property settings.
/// </summary>
/// <param name="name">The name of the button.</param>
/// <param name="text">The button label.</param>
public TaskDialogButton(string name, string text) : base(name, text) { }
private bool useElevationIcon;
/// <summary>
/// Gets or sets a value that controls whether the elevation icon is displayed.
/// </summary>
public bool UseElevationIcon
{
get { return useElevationIcon; }
set
{
CheckPropertyChangeAllowed("ShowElevationIcon");
useElevationIcon = value;
ApplyPropertyChange("ShowElevationIcon");
}
}
}
}

Просмотреть файл

@ -0,0 +1,112 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
// ContentProperty allows us to specify the text
// of the button as the child text of
// a button element in XAML, as well as explicitly
// set with 'Text="<text>"'
// Note that this attribute is inherited, so it
// applies to command-links and radio buttons as well.
/// <summary>
/// Defines the abstract base class for task dialog buttons.
/// Classes that inherit from this class will inherit
/// the Text property defined in this class.
/// </summary>
public abstract class TaskDialogButtonBase : TaskDialogControl
{
/// <summary>
/// Creates a new instance on a task dialog button.
/// </summary>
protected TaskDialogButtonBase() { }
/// <summary>
/// Creates a new instance on a task dialog button with
/// the specified name and text.
/// </summary>
/// <param name="name">The name for this button.</param>
/// <param name="text">The label for this button.</param>
protected TaskDialogButtonBase(string name, string text) : base(name)
{
this.text = text;
}
// Note that we don't need to explicitly
// implement the add/remove delegate for the Click event;
// the hosting dialog only needs the delegate
// information when the Click event is
// raised (indirectly) by NativeTaskDialog,
// so the latest delegate is always available.
/// <summary>
/// Raised when the task dialog button is clicked.
/// </summary>
public event EventHandler Click;
internal void RaiseClickEvent()
{
// Only perform click if the button is enabled.
if (!enabled) { return; }
if (Click != null) { Click(this, EventArgs.Empty); }
}
private string text;
/// <summary>
/// Gets or sets the button text.
/// </summary>
public string Text
{
get { return text; }
set
{
CheckPropertyChangeAllowed("Text");
text = value;
ApplyPropertyChange("Text");
}
}
private bool enabled = true;
/// <summary>
/// Gets or sets a value that determines whether the
/// button is enabled. The enabled state can cannot be changed
/// before the dialog is shown.
/// </summary>
public bool Enabled
{
get { return enabled; }
set
{
CheckPropertyChangeAllowed("Enabled");
enabled = value;
ApplyPropertyChange("Enabled");
}
}
private bool defaultControl;
/// <summary>
/// Gets or sets a value that indicates whether
/// this button is the default button.
/// </summary>
public bool Default
{
get { return defaultControl; }
set
{
CheckPropertyChangeAllowed("Default");
defaultControl = value;
ApplyPropertyChange("Default");
}
}
/// <summary>
/// Returns the Text property value for this button.
/// </summary>
/// <returns>A <see cref="System.String"/>.</returns>
public override string ToString()
{
return text ?? string.Empty;
}
}
}

Просмотреть файл

@ -0,0 +1,34 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System.ComponentModel;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Data associated with <see cref="TaskDialog.Closing"/> event.
/// </summary>
public class TaskDialogClosingEventArgs : CancelEventArgs
{
private TaskDialogResult taskDialogResult;
/// <summary>
/// Gets or sets the standard button that was clicked.
/// </summary>
public TaskDialogResult TaskDialogResult
{
get { return taskDialogResult; }
set { taskDialogResult = value; }
}
private string customButton;
/// <summary>
/// Gets or sets the text of the custom button that was clicked.
/// </summary>
public string CustomButton
{
get { return customButton; }
set { customButton = value; }
}
}
}

Просмотреть файл

@ -0,0 +1,59 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Globalization;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Represents a command-link.
/// </summary>
public class TaskDialogCommandLink : TaskDialogButton
{
/// <summary>
/// Creates a new instance of this class.
/// </summary>
public TaskDialogCommandLink() { }
/// <summary>
/// Creates a new instance of this class with the specified name and label.
/// </summary>
/// <param name="name">The name for this button.</param>
/// <param name="text">The label for this button.</param>
public TaskDialogCommandLink(string name, string text) : base(name, text) { }
/// <summary>
/// Creates a new instance of this class with the specified name,label, and instruction.
/// </summary>
/// <param name="name">The name for this button.</param>
/// <param name="text">The label for this button.</param>
/// <param name="instruction">The instruction for this command link.</param>
public TaskDialogCommandLink(string name, string text, string instruction)
: base(name, text)
{
this.instruction = instruction;
}
private string instruction;
/// <summary>
/// Gets or sets the instruction associated with this command link button.
/// </summary>
public string Instruction
{
get { return instruction; }
set { instruction = value; }
}
/// <summary>
/// Returns a string representation of this object.
/// </summary>
/// <returns>A <see cref="System.String"/></returns>
public override string ToString()
{
return string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}",
Text ?? string.Empty,
(!string.IsNullOrEmpty(Text) && !string.IsNullOrEmpty(instruction)) ? Environment.NewLine : string.Empty,
instruction ?? string.Empty);
}
}
}

Просмотреть файл

@ -0,0 +1,20 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Declares the abstract base class for all custom task dialog controls.
/// </summary>
public abstract class TaskDialogControl : DialogControl
{
/// <summary>
/// Creates a new instance of a task dialog control.
/// </summary>
protected TaskDialogControl() { }
/// <summary>
/// Creates a new instance of a task dialog control with the specified name.
/// </summary>
/// <param name="name">The name for this control.</param>
protected TaskDialogControl(string name) : base(name) { }
}
}

Просмотреть файл

@ -0,0 +1,23 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
internal static class TaskDialogDefaults
{
public static string Caption { get { return LocalizedMessages.TaskDialogDefaultCaption; } }
public static string MainInstruction { get { return LocalizedMessages.TaskDialogDefaultMainInstruction; } }
public static string Content { get { return LocalizedMessages.TaskDialogDefaultContent; } }
public const int ProgressBarMinimumValue = 0;
public const int ProgressBarMaximumValue = 100;
public const int IdealWidth = 0;
// For generating control ID numbers that won't
// collide with the standard button return IDs.
public const int MinimumDialogControlId =
(int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close + 1;
}
}

Просмотреть файл

@ -0,0 +1,25 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Specifies the options for expand/collapse sections in dialogs.
/// </summary>
public enum TaskDialogExpandedDetailsLocation
{
/// <summary>
/// Do not show the content.
/// </summary>
Hide,
/// <summary>
/// Show the content.
/// </summary>
ExpandContent,
/// <summary>
/// Expand the footer content.
/// </summary>
ExpandFooter
}
}

Просмотреть файл

@ -0,0 +1,26 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Defines event data associated with a HyperlinkClick event.
/// </summary>
public class TaskDialogHyperlinkClickedEventArgs : EventArgs
{
/// <summary>
/// Creates a new instance of this class with the specified link text.
/// </summary>
/// <param name="linkText">The text of the hyperlink that was clicked.</param>
public TaskDialogHyperlinkClickedEventArgs(string linkText)
{
LinkText = linkText;
}
/// <summary>
/// Gets or sets the text of the hyperlink that was clicked.
/// </summary>
public string LinkText { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,123 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Provides a visual representation of the progress of a long running operation.
/// </summary>
public class TaskDialogProgressBar : TaskDialogBar
{
/// <summary>
/// Creates a new instance of this class.
/// </summary>
public TaskDialogProgressBar() { }
/// <summary>
/// Creates a new instance of this class with the specified name.
/// And using the default values: Min = 0, Max = 100, Current = 0
/// </summary>
/// <param name="name">The name of the control.</param>
public TaskDialogProgressBar(string name) : base(name) { }
/// <summary>
/// Creates a new instance of this class with the specified
/// minimum, maximum and current values.
/// </summary>
/// <param name="minimum">The minimum value for this control.</param>
/// <param name="maximum">The maximum value for this control.</param>
/// <param name="value">The current value for this control.</param>
public TaskDialogProgressBar(int minimum, int maximum, int value)
{
Minimum = minimum;
Maximum = maximum;
Value = value;
}
private int _minimum;
private int _value;
private int _maximum = TaskDialogDefaults.ProgressBarMaximumValue;
/// <summary>
/// Gets or sets the minimum value for the control.
/// </summary>
public int Minimum
{
get { return _minimum; }
set
{
CheckPropertyChangeAllowed("Minimum");
// Check for positive numbers
if (value < 0)
{
throw new System.ArgumentException(LocalizedMessages.TaskDialogProgressBarMinValueGreaterThanZero, "value");
}
// Check if min / max differ
if (value >= Maximum)
{
throw new System.ArgumentException(LocalizedMessages.TaskDialogProgressBarMinValueLessThanMax, "value");
}
_minimum = value;
ApplyPropertyChange("Minimum");
}
}
/// <summary>
/// Gets or sets the maximum value for the control.
/// </summary>
public int Maximum
{
get { return _maximum; }
set
{
CheckPropertyChangeAllowed("Maximum");
// Check if min / max differ
if (value < Minimum)
{
throw new System.ArgumentException(LocalizedMessages.TaskDialogProgressBarMaxValueGreaterThanMin, "value");
}
_maximum = value;
ApplyPropertyChange("Maximum");
}
}
/// <summary>
/// Gets or sets the current value for the control.
/// </summary>
public int Value
{
get { return this._value; }
set
{
CheckPropertyChangeAllowed("Value");
// Check for positive numbers
if (value < Minimum || value > Maximum)
{
throw new System.ArgumentException(LocalizedMessages.TaskDialogProgressBarValueInRange, "value");
}
this._value = value;
ApplyPropertyChange("Value");
}
}
/// <summary>
/// Verifies that the progress bar's value is between its minimum and maximum.
/// </summary>
internal bool HasValidValues
{
get { return _minimum <= _value && _value <= _maximum; }
}
/// <summary>
/// Resets the control to its minimum value.
/// </summary>
protected internal override void Reset()
{
base.Reset();
_value = _minimum;
}
}
}

Просмотреть файл

@ -0,0 +1,35 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Sets the state of a task dialog progress bar.
/// </summary>
public enum TaskDialogProgressBarState
{
/// <summary>
/// Uninitialized state, this should never occur.
/// </summary>
None = 0,
/// <summary>
/// Normal state.
/// </summary>
Normal = TaskDialogNativeMethods.ProgressBarState.Normal,
/// <summary>
/// An error occurred.
/// </summary>
Error = TaskDialogNativeMethods.ProgressBarState.Error,
/// <summary>
/// The progress is paused.
/// </summary>
Paused = TaskDialogNativeMethods.ProgressBarState.Paused,
/// <summary>
/// Displays marquee (indeterminate) style progress
/// </summary>
Marquee
}
}

Просмотреть файл

@ -0,0 +1,25 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Defines a radio button that can be hosted in by a
/// <see cref="TaskDialog"/> object.
/// </summary>
public class TaskDialogRadioButton : TaskDialogButtonBase
{
/// <summary>
/// Creates a new instance of this class.
/// </summary>
public TaskDialogRadioButton() { }
/// <summary>
/// Creates a new instance of this class with
/// the specified name and text.
/// </summary>
/// <param name="name">The name for this control.</param>
/// <param name="text">The value for this controls
/// <see cref="P:Microsoft.WindowsAPICodePack.Dialogs.TaskDialogButtonBase.Text"/> property.</param>
public TaskDialogRadioButton(string name, string text) : base(name, text) { }
}
}

Просмотреть файл

@ -0,0 +1,50 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Indicates the various buttons and options clicked by the user on the task dialog.
/// </summary>
public enum TaskDialogResult
{
/// <summary>
/// No button was selected.
/// </summary>
None = 0x0000,
/// <summary>
/// "OK" button was clicked
/// </summary>
Ok = 0x0001,
/// <summary>
/// "Yes" button was clicked
/// </summary>
Yes = 0x0002,
/// <summary>
/// "No" button was clicked
/// </summary>
No = 0x0004,
/// <summary>
/// "Cancel" button was clicked
/// </summary>
Cancel = 0x0008,
/// <summary>
/// "Retry" button was clicked
/// </summary>
Retry = 0x0010,
/// <summary>
/// "Close" button was clicked
/// </summary>
Close = 0x0020,
/// <summary>
/// A custom button was clicked.
/// </summary>
CustomButtonClicked = 0x0100,
}
}

Просмотреть файл

@ -0,0 +1,49 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Identifies one of the standard buttons that
/// can be displayed via TaskDialog.
/// </summary>
[Flags]
public enum TaskDialogStandardButtons
{
/// <summary>
/// No buttons on the dialog.
/// </summary>
None = 0x0000,
/// <summary>
/// An "OK" button.
/// </summary>
Ok = 0x0001,
/// <summary>
/// A "Yes" button.
/// </summary>
Yes = 0x0002,
/// <summary>
/// A "No" button.
/// </summary>
No = 0x0004,
/// <summary>
/// A "Cancel" button.
/// </summary>
Cancel = 0x0008,
/// <summary>
/// A "Retry" button.
/// </summary>
Retry = 0x0010,
/// <summary>
/// A "Close" button.
/// </summary>
Close = 0x0020
}
}

Просмотреть файл

@ -0,0 +1,35 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Specifies the icon displayed in a task dialog.
/// </summary>
public enum TaskDialogStandardIcon
{
/// <summary>
/// Displays no icons (default).
/// </summary>
None = 0,
/// <summary>
/// Displays the warning icon.
/// </summary>
Warning = 65535,
/// <summary>
/// Displays the error icon.
/// </summary>
Error = 65534,
/// <summary>
/// Displays the Information icon.
/// </summary>
Information = 65533,
/// <summary>
/// Displays the User Account Control shield.
/// </summary>
Shield = 65532
}
}

Просмотреть файл

@ -0,0 +1,20 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Specifies the initial display location for a task dialog.
/// </summary>
public enum TaskDialogStartupLocation
{
/// <summary>
/// The window placed in the center of the screen.
/// </summary>
CenterScreen,
/// <summary>
/// The window centered relative to the window that launched the dialog.
/// </summary>
CenterOwner
}
}

Просмотреть файл

@ -0,0 +1,26 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// The event data for a TaskDialogTick event.
/// </summary>
public class TaskDialogTickEventArgs : EventArgs
{
/// <summary>
/// Initializes the data associated with the TaskDialog tick event.
/// </summary>
/// <param name="ticks">The total number of ticks since the control was activated.</param>
public TaskDialogTickEventArgs(int ticks)
{
Ticks = ticks;
}
/// <summary>
/// Gets a value that determines the current number of ticks.
/// </summary>
public int Ticks { get; private set; }
}
}

100
Core/GlobalSuppressions.cs Normal file
Просмотреть файл

@ -0,0 +1,100 @@
// This file is used by Code Analysis to maintain SuppressMessage
// attributes that are applied to this project.
// Project-level suppressions either have no target or are given
// a specific target and scoped to a namespace, type, member, etc.
//
// To add a suppression to this file, right-click the message in the
// Error List, point to "Suppress Message(s)", and click
// "In Project Suppression File".
// You do not need to add suppressions to this file manually.
#region CA1709 Identifers should use proper casing - "API" acronym chosen for clarity
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "API")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "namespace", Target = "Microsoft.WindowsAPICodePack.ApplicationServices", MessageId = "API")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "namespace", Target = "Microsoft.WindowsAPICodePack.Net", MessageId = "API")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "namespace", Target = "Microsoft.WindowsAPICodePack.Shell.PropertySystem", MessageId = "API")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "namespace", Target = "Microsoft.WindowsAPICodePack.Dialogs", MessageId = "API")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "namespace", Target = "MS.WindowsAPICodePack.Internal", MessageId = "API")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "namespace", Target = "Microsoft.WindowsAPICodePack.Shell.PropertySystem", MessageId = "API")]
#endregion
#region CA1709 - Identifiers should use proper casing - "v" for "Version" chosen for clarity
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv6Internet", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv6NoTraffic", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv4Subnet", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv4NoTraffic", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv4Internet", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv4LocalNetwork", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv6Subnet", MessageId = "Pv")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Net.ConnectivityStates.#IPv6LocalNetwork", MessageId = "Pv")]
#endregion
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields", Scope = "member", Target = "Microsoft.WindowsAPICodePack.ApplicationServices.PowerPersonalityGuids.#All")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1805:DoNotInitializeUnnecessarily", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#.cctor()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Microsoft.WindowsAPICodePack.Resources.LocalizedMessages.resources", MessageId = "comctl")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Microsoft.WindowsAPICodePack.Resources.LocalizedMessages.resources", MessageId = "Wh")]
#region CA1811 - Potentially uncalled code
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Shell.PropertySystem.PropVariantNativeMethods.#InitPropVariantFromPropVariantVectorElem(MS.WindowsAPICodePack.Internal.PropVariant,System.UInt32,MS.WindowsAPICodePack.Internal.PropVariant)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.DialogsDefaults.#get_Caption()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.DialogsDefaults.#get_Content()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreErrorHelper.#HResultFromWin32(System.Int32)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreErrorHelper.#Failed(System.Int32)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods+Size.#get_Height()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods+Size.#set_Height(System.Int32)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods+Size.#set_Width(System.Int32)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods+Size.#get_Width()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.DialogsDefaults.#get_MainInstruction()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialogSettings.#get_InvokeHelp()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialog.#get_SelectedRadioButtonId()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.TaskDialogNativeMethods+IconUnion.#get_MainIcon()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#SendMessage(System.IntPtr,MS.WindowsAPICodePack.Internal.WindowMessage,System.IntPtr,System.IntPtr)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#SendMessage(System.IntPtr,System.UInt32,System.IntPtr,System.String)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#SendMessage(System.IntPtr,System.UInt32,System.Int32,System.String)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#GetLoWord(System.Int64)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#GetHiWord(System.Int64,System.Int32)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#PostMessage(System.IntPtr,MS.WindowsAPICodePack.Internal.WindowMessage,System.IntPtr,System.IntPtr)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreNativeMethods.#SendMessage(System.IntPtr,System.UInt32,System.Int32&,System.Text.StringBuilder)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.CoreErrorHelper.#Matches(System.Int32,System.Int32)")]
#endregion
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1014:MarkAssembliesWithClsCompliant", Justification = "There are places where unsigned values are used, which is considered not Cls compliant.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA2210:AssembliesShouldHaveValidStrongNames")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1020:AvoidNamespacesWithFewTypes", Scope = "namespace", Target = "Microsoft.WindowsAPICodePack.Shell.PropertySystem", Justification = "Uses nested classes to organize the namespce, there is a workitem to resolve this.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1027:MarkEnumsWithFlags", Scope = "type", Target = "Microsoft.WindowsAPICodePack.Dialogs.TaskDialogResult", Justification = "Does not represent flags.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#Value", Justification = "Uses a switch statement.")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope = "member", Justification = "These return snapshots of a state, which are likely to change between calls.", Target = "Microsoft.WindowsAPICodePack.ApplicationServices.PowerManager.#GetCurrentBatteryState()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Scope = "member", Justification = "These return snapshots of a state, which are likely to change between calls.", Target = "Microsoft.WindowsAPICodePack.Net.NetworkListManager.#GetNetworkConnections()")]
#region CA2122, CA2123 - LinkDemand related
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#.ctor(System.Single[])")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#.ctor(System.Decimal[])")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.ApplicationServices.ApplicationRestartRecoveryManager.#RegisterForApplicationRecovery(Microsoft.WindowsAPICodePack.ApplicationServices.RecoverySettings)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialog.#AllocateAndMarshalButtons(Microsoft.WindowsAPICodePack.Dialogs.TaskDialogNativeMethods+TaskDialogButton[])")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialog.#Dispose(System.Boolean)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialog.#FreeOldString(Microsoft.WindowsAPICodePack.Dialogs.TaskDialogNativeMethods+TaskDialogElements)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialog.#MakeNewString(System.String,Microsoft.WindowsAPICodePack.Dialogs.TaskDialogNativeMethods+TaskDialogElements)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialog.#NativeShow()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.NativeTaskDialogSettings.#.ctor()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#GetBlobData()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#.ctor(System.String)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.PropVariant.#Value")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.SafeWindowHandle.#ReleaseHandle()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.ApplicationServices.Power.#GetSystemBatteryState()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "Microsoft.WindowsAPICodePack.ApplicationServices.Power.#GetSystemPowerCapabilities()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.ZeroInvalidHandle.#.ctor()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.SafeIconHandle.#ReleaseHandle()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.SafeRegionHandle.#ReleaseHandle()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.SafeWindowHandle.#ReleaseHandle()")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase", Scope = "member", Target = "MS.WindowsAPICodePack.Internal.ZeroInvalidHandle.#IsInvalid")]
#endregion
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Interoperability", "CA1400:PInvokeEntryPointsShouldExist", Scope = "member", Target = "Microsoft.WindowsAPICodePack.Dialogs.TaskDialogNativeMethods.#TaskDialogIndirect(Microsoft.WindowsAPICodePack.Dialogs.TaskDialogNativeMethods+TaskDialogConfiguration,System.Int32&,System.Int32&,System.Boolean&)", Justification="This does exist, I believe it is caused by FxCop using the wrong version of the DLL.")]

Просмотреть файл

@ -0,0 +1,65 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
internal static class AppRestartRecoveryNativeMethods
{
#region Application Restart and Recovery Definitions
internal delegate UInt32 InternalRecoveryCallback(IntPtr state);
private static InternalRecoveryCallback internalCallback = new InternalRecoveryCallback(InternalRecoveryHandler);
internal static InternalRecoveryCallback InternalCallback { get { return internalCallback; } }
private static UInt32 InternalRecoveryHandler(IntPtr parameter)
{
bool cancelled = false;
ApplicationRecoveryInProgress(out cancelled);
GCHandle handle = GCHandle.FromIntPtr(parameter);
RecoveryData data = handle.Target as RecoveryData;
data.Invoke();
handle.Free();
return (0);
}
[DllImport("kernel32.dll")]
internal static extern void ApplicationRecoveryFinished(
[MarshalAs(UnmanagedType.Bool)] bool success);
[DllImport("kernel32.dll")]
[PreserveSig]
internal static extern HResult ApplicationRecoveryInProgress(
[Out, MarshalAs(UnmanagedType.Bool)] out bool canceled);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
[PreserveSig]
internal static extern HResult RegisterApplicationRecoveryCallback(
InternalRecoveryCallback callback, IntPtr param,
uint pingInterval,
uint flags); // Unused.
[DllImport("kernel32.dll")]
[PreserveSig]
internal static extern HResult RegisterApplicationRestart(
[MarshalAs(UnmanagedType.BStr)] string commandLineArgs,
RestartRestrictions flags);
[DllImport("kernel32.dll")]
[PreserveSig]
internal static extern HResult UnregisterApplicationRecoveryCallback();
[DllImport("kernel32.dll")]
[PreserveSig]
internal static extern HResult UnregisterApplicationRestart();
#endregion
}
}

Просмотреть файл

@ -0,0 +1,161 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// HRESULT Wrapper
/// </summary>
public enum HResult
{
/// <summary>
/// S_OK
/// </summary>
Ok = 0x0000,
/// <summary>
/// S_FALSE
/// </summary>
False = 0x0001,
/// <summary>
/// E_INVALIDARG
/// </summary>
InvalidArguments = unchecked((int)0x80070057),
/// <summary>
/// E_OUTOFMEMORY
/// </summary>
OutOfMemory = unchecked((int)0x8007000E),
/// <summary>
/// E_NOINTERFACE
/// </summary>
NoInterface = unchecked((int)0x80004002),
/// <summary>
/// E_FAIL
/// </summary>
Fail = unchecked((int)0x80004005),
/// <summary>
/// E_ELEMENTNOTFOUND
/// </summary>
ElementNotFound = unchecked((int)0x80070490),
/// <summary>
/// TYPE_E_ELEMENTNOTFOUND
/// </summary>
TypeElementNotFound = unchecked((int)0x8002802B),
/// <summary>
/// NO_OBJECT
/// </summary>
NoObject = unchecked((int)0x800401E5),
/// <summary>
/// Win32 Error code: ERROR_CANCELLED
/// </summary>
Win32ErrorCanceled = 1223,
/// <summary>
/// ERROR_CANCELLED
/// </summary>
Canceled = unchecked((int)0x800704C7),
/// <summary>
/// The requested resource is in use
/// </summary>
ResourceInUse = unchecked((int)0x800700AA),
/// <summary>
/// The requested resources is read-only.
/// </summary>
AccessDenied = unchecked((int)0x80030005)
}
/// <summary>
/// Provide Error Message Helper Methods.
/// This is intended for Library Internal use only.
/// </summary>
internal static class CoreErrorHelper
{
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
private const int FacilityWin32 = 7;
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
public const int Ignored = (int)HResult.Ok;
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
/// <param name="win32ErrorCode">The Windows API error code.</param>
/// <returns>The equivalent HRESULT.</returns>
public static int HResultFromWin32(int win32ErrorCode)
{
if (win32ErrorCode > 0)
{
win32ErrorCode =
(int)(((uint)win32ErrorCode & 0x0000FFFF) | (FacilityWin32 << 16) | 0x80000000);
}
return win32ErrorCode;
}
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
/// <param name="result">The error code.</param>
/// <returns>True if the error code indicates success.</returns>
public static bool Succeeded(int result)
{
return result >= 0;
}
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
/// <param name="result">The error code.</param>
/// <returns>True if the error code indicates success.</returns>
public static bool Succeeded(HResult result)
{
return Succeeded((int)result);
}
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
/// <param name="result">The error code.</param>
/// <returns>True if the error code indicates failure.</returns>
public static bool Failed(HResult result)
{
return !Succeeded(result);
}
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
/// <param name="result">The error code.</param>
/// <returns>True if the error code indicates failure.</returns>
public static bool Failed(int result)
{
return !Succeeded(result);
}
/// <summary>
/// This is intended for Library Internal use only.
/// </summary>
/// <param name="result">The COM error code.</param>
/// <param name="win32ErrorCode">The Win32 error code.</param>
/// <returns>Inticates that the Win32 error code corresponds to the COM error code.</returns>
public static bool Matches(int result, int win32ErrorCode)
{
return (result == HResultFromWin32(win32ErrorCode));
}
}
}

118
Core/Interop/CoreHelpers.cs Normal file
Просмотреть файл

@ -0,0 +1,118 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Globalization;
using System.Text;
using Microsoft.WindowsAPICodePack.Resources;
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Common Helper methods
/// </summary>
public static class CoreHelpers
{
/// <summary>
/// Determines if the application is running on XP
/// </summary>
public static bool RunningOnXP
{
get
{
return Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion.Version.Major >= 5;
}
}
/// <summary>
/// Throws PlatformNotSupportedException if the application is not running on Windows XP
/// </summary>
public static void ThrowIfNotXP()
{
if (!CoreHelpers.RunningOnXP)
{
throw new PlatformNotSupportedException(LocalizedMessages.CoreHelpersRunningOnXp);
}
}
/// <summary>
/// Determines if the application is running on Vista
/// </summary>
public static bool RunningOnVista
{
get
{
return Environment.OSVersion.Version.Major >= 6;
}
}
/// <summary>
/// Throws PlatformNotSupportedException if the application is not running on Windows Vista
/// </summary>
public static void ThrowIfNotVista()
{
if (!CoreHelpers.RunningOnVista)
{
throw new PlatformNotSupportedException(LocalizedMessages.CoreHelpersRunningOnVista);
}
}
/// <summary>
/// Determines if the application is running on Windows 7
/// </summary>
public static bool RunningOnWin7
{
get
{
// Verifies that OS version is 6.1 or greater, and the Platform is WinNT.
return Environment.OSVersion.Platform == PlatformID.Win32NT &&
Environment.OSVersion.Version.CompareTo(new Version(6, 1)) >= 0;
}
}
/// <summary>
/// Throws PlatformNotSupportedException if the application is not running on Windows 7
/// </summary>
public static void ThrowIfNotWin7()
{
if (!CoreHelpers.RunningOnWin7)
{
throw new PlatformNotSupportedException(LocalizedMessages.CoreHelpersRunningOn7);
}
}
/// <summary>
/// Get a string resource given a resource Id
/// </summary>
/// <param name="resourceId">The resource Id</param>
/// <returns>The string resource corresponding to the given resource Id. Returns null if the resource id
/// is invalid or the string cannot be retrieved for any other reason.</returns>
public static string GetStringResource(string resourceId)
{
string[] parts;
string library;
int index;
if (string.IsNullOrEmpty(resourceId)) { return string.Empty; }
// Known folder "Recent" has a malformed resource id
// for its tooltip. This causes the resource id to
// parse into 3 parts instead of 2 parts if we don't fix.
resourceId = resourceId.Replace("shell32,dll", "shell32.dll");
parts = resourceId.Split(new char[] { ',' });
library = parts[0];
library = library.Replace(@"@", string.Empty);
library = Environment.ExpandEnvironmentVariables(library);
IntPtr handle = CoreNativeMethods.LoadLibrary(library);
parts[1] = parts[1].Replace("-", string.Empty);
index = int.Parse(parts[1], CultureInfo.InvariantCulture);
StringBuilder stringValue = new StringBuilder(255);
int retval = CoreNativeMethods.LoadString(handle, index, stringValue, 255);
return retval != 0 ? stringValue.ToString() : null;
}
}
}

Просмотреть файл

@ -0,0 +1,280 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Wrappers for Native Methods and Structs.
/// This type is intended for internal use only
/// </summary>
internal static class CoreNativeMethods
{
#region General Definitions
/// <summary>
/// Places (posts) a message in the message queue associated with the thread that created
/// the specified window and returns without waiting for the thread to process the message.
/// </summary>
/// <param name="windowHandle">Handle to the window whose window procedure will receive the message.
/// If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system,
/// including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
/// but the message is not sent to child windows.
/// </param>
/// <param name="message">Specifies the message to be sent.</param>
/// <param name="wparam">Specifies additional message-specific information.</param>
/// <param name="lparam">Specifies additional message-specific information.</param>
/// <returns>A return code specific to the message being sent.</returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, PreserveSig=false, SetLastError = true)]
public static extern void PostMessage(
IntPtr windowHandle,
WindowMessage message,
IntPtr wparam,
IntPtr lparam
);
/// <summary>
/// Sends the specified message to a window or windows. The SendMessage function calls
/// the window procedure for the specified window and does not return until the window
/// procedure has processed the message.
/// </summary>
/// <param name="windowHandle">Handle to the window whose window procedure will receive the message.
/// If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system,
/// including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
/// but the message is not sent to child windows.
/// </param>
/// <param name="message">Specifies the message to be sent.</param>
/// <param name="wparam">Specifies additional message-specific information.</param>
/// <param name="lparam">Specifies additional message-specific information.</param>
/// <returns>A return code specific to the message being sent.</returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(
IntPtr windowHandle,
WindowMessage message,
IntPtr wparam,
IntPtr lparam
);
/// <summary>
/// Sends the specified message to a window or windows. The SendMessage function calls
/// the window procedure for the specified window and does not return until the window
/// procedure has processed the message.
/// </summary>
/// <param name="windowHandle">Handle to the window whose window procedure will receive the message.
/// If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system,
/// including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
/// but the message is not sent to child windows.
/// </param>
/// <param name="message">Specifies the message to be sent.</param>
/// <param name="wparam">Specifies additional message-specific information.</param>
/// <param name="lparam">Specifies additional message-specific information.</param>
/// <returns>A return code specific to the message being sent.</returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(
IntPtr windowHandle,
uint message,
IntPtr wparam,
IntPtr lparam
);
/// <summary>
/// Sends the specified message to a window or windows. The SendMessage function calls
/// the window procedure for the specified window and does not return until the window
/// procedure has processed the message.
/// </summary>
/// <param name="windowHandle">Handle to the window whose window procedure will receive the message.
/// If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system,
/// including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
/// but the message is not sent to child windows.
/// </param>
/// <param name="message">Specifies the message to be sent.</param>
/// <param name="wparam">Specifies additional message-specific information.</param>
/// <param name="lparam">Specifies additional message-specific information.</param>
/// <returns>A return code specific to the message being sent.</returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(
IntPtr windowHandle,
uint message,
IntPtr wparam,
[MarshalAs(UnmanagedType.LPWStr)] string lparam);
/// <summary>
/// Sends the specified message to a window or windows. The SendMessage function calls
/// the window procedure for the specified window and does not return until the window
/// procedure has processed the message.
/// </summary>
/// <param name="windowHandle">Handle to the window whose window procedure will receive the message.
/// If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system,
/// including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
/// but the message is not sent to child windows.
/// </param>
/// <param name="message">Specifies the message to be sent.</param>
/// <param name="wparam">Specifies additional message-specific information.</param>
/// <param name="lparam">Specifies additional message-specific information.</param>
/// <returns>A return code specific to the message being sent.</returns>
public static IntPtr SendMessage(
IntPtr windowHandle,
uint message,
int wparam,
string lparam)
{
return SendMessage(windowHandle, message, (IntPtr)wparam, lparam);
}
/// <summary>
/// Sends the specified message to a window or windows. The SendMessage function calls
/// the window procedure for the specified window and does not return until the window
/// procedure has processed the message.
/// </summary>
/// <param name="windowHandle">Handle to the window whose window procedure will receive the message.
/// If this parameter is HWND_BROADCAST, the message is sent to all top-level windows in the system,
/// including disabled or invisible unowned windows, overlapped windows, and pop-up windows;
/// but the message is not sent to child windows.
/// </param>
/// <param name="message">Specifies the message to be sent.</param>
/// <param name="wparam">Specifies additional message-specific information.</param>
/// <param name="lparam">Specifies additional message-specific information.</param>
/// <returns>A return code specific to the message being sent.</returns>
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr SendMessage(
IntPtr windowHandle,
uint message,
ref int wparam,
[MarshalAs(UnmanagedType.LPWStr)] StringBuilder lparam);
// Various helpers for forcing binding to proper
// version of Comctl32 (v6).
[DllImport("kernel32.dll", SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)]
internal static extern IntPtr LoadLibrary([MarshalAs(UnmanagedType.LPStr)] string fileName);
[DllImport("gdi32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DeleteObject(IntPtr graphicsObjectHandle);
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern int LoadString(
IntPtr instanceHandle,
int id,
StringBuilder buffer,
int bufferSize);
[DllImport("Kernel32.dll", EntryPoint = "LocalFree")]
internal static extern IntPtr LocalFree(ref Guid guid);
/// <summary>
/// Destroys an icon and frees any memory the icon occupied.
/// </summary>
/// <param name="hIcon">Handle to the icon to be destroyed. The icon must not be in use. </param>
/// <returns>If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError. </returns>
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool DestroyIcon(IntPtr hIcon);
#endregion
#region Window Handling
[DllImport("user32.dll", SetLastError = true, EntryPoint = "DestroyWindow", CallingConvention = CallingConvention.StdCall)]
internal static extern int DestroyWindow(IntPtr handle);
#endregion
#region General Declarations
// Various important window messages
internal const int UserMessage = 0x0400;
internal const int EnterIdleMessage = 0x0121;
// FormatMessage constants and structs.
internal const int FormatMessageFromSystem = 0x00001000;
// App recovery and restart return codes
internal const uint ResultFailed = 0x80004005;
internal const uint ResultInvalidArgument = 0x80070057;
internal const uint ResultFalse = 1;
internal const uint ResultNotFound = 0x80070490;
/// <summary>
/// Gets the HiWord
/// </summary>
/// <param name="value">The value to get the hi word from.</param>
/// <param name="size">Size</param>
/// <returns>The upper half of the dword.</returns>
public static int GetHiWord(long value, int size)
{
return (short)(value >> size);
}
/// <summary>
/// Gets the LoWord
/// </summary>
/// <param name="value">The value to get the low word from.</param>
/// <returns>The lower half of the dword.</returns>
public static int GetLoWord(long value)
{
return (short)(value & 0xFFFF);
}
#endregion
#region GDI and DWM Declarations
/// <summary>
/// A Wrapper for a SIZE struct
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct Size
{
private int width;
private int height;
/// <summary>
/// Width
/// </summary>
public int Width { get { return width; } set { width = value; } }
/// <summary>
/// Height
/// </summary>
public int Height { get { return height; } set { height = value; } }
};
// Enable/disable non-client rendering based on window style.
internal const int DWMNCRP_USEWINDOWSTYLE = 0;
// Disabled non-client rendering; window style is ignored.
internal const int DWMNCRP_DISABLED = 1;
// Enabled non-client rendering; window style is ignored.
internal const int DWMNCRP_ENABLED = 2;
// Enable/disable non-client rendering Use DWMNCRP_* values.
internal const int DWMWA_NCRENDERING_ENABLED = 1;
// Non-client rendering policy.
internal const int DWMWA_NCRENDERING_POLICY = 2;
// Potentially enable/forcibly disable transitions 0 or 1.
internal const int DWMWA_TRANSITIONS_FORCEDISABLED = 3;
#endregion
#region Windows OS structs and consts
internal const uint StatusAccessDenied = 0xC0000022;
public delegate int WNDPROC(IntPtr hWnd,
uint uMessage,
IntPtr wParam,
IntPtr lParam);
#endregion
}
}

Просмотреть файл

@ -0,0 +1,30 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Dialog Show State
/// </summary>
public enum DialogShowState
{
/// <summary>
/// Pre Show
/// </summary>
PreShow,
/// <summary>
/// Currently Showing
/// </summary>
Showing,
/// <summary>
/// Currently Closing
/// </summary>
Closing,
/// <summary>
/// Closed
/// </summary>
Closed
}
}

Просмотреть файл

@ -0,0 +1,67 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
[ComImport]
[TypeLibType((short)0x1040)]
[Guid("DCB00002-570F-4A9B-8D69-199FDBA5723B")]
internal interface INetwork
{
[return: MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
string GetName();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetName([In, MarshalAs(UnmanagedType.BStr)] string szNetworkNewName);
[return: MarshalAs(UnmanagedType.BStr)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
string GetDescription();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetDescription([In, MarshalAs(UnmanagedType.BStr)] string szDescription);
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
Guid GetNetworkId();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
DomainType GetDomainType();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
IEnumerable GetNetworkConnections();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void GetTimeCreatedAndConnected(
out uint pdwLowDateTimeCreated,
out uint pdwHighDateTimeCreated,
out uint pdwLowDateTimeConnected,
out uint pdwHighDateTimeConnected);
bool IsConnectedToInternet
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
get;
}
bool IsConnected
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
get;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
ConnectivityStates GetConnectivity();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
NetworkCategory GetCategory();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
void SetCategory([In] NetworkCategory NewCategory);
}
}

Просмотреть файл

@ -0,0 +1,43 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
[ComImport]
[TypeLibType((short)0x1040)]
[Guid("DCB00005-570F-4A9B-8D69-199FDBA5723B")]
internal interface INetworkConnection
{
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
INetwork GetNetwork();
bool IsConnectedToInternet
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
get;
}
bool IsConnected
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
get;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
ConnectivityStates GetConnectivity();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
Guid GetConnectionId();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
Guid GetAdapterId();
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
DomainType GetDomainType();
}
}

Просмотреть файл

@ -0,0 +1,46 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
[ComImport]
[Guid("DCB00000-570F-4A9B-8D69-199FDBA5723B")]
[TypeLibType((short)0x1040)]
internal interface INetworkListManager
{
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
INetwork GetNetwork([In] Guid gdNetworkId);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
IEnumerable GetNetworkConnections();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId);
bool IsConnectedToInternet
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
get;
}
bool IsConnected
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
get;
}
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
ConnectivityStates GetConnectivity();
}
}

Просмотреть файл

@ -0,0 +1,47 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
[ComImport, ClassInterface((short)0), Guid("DCB00C01-570F-4A9B-8D69-199FDBA5723B")]
[ComSourceInterfaces("Microsoft.Windows.NetworkList.Internal.INetworkEvents\0Microsoft.Windows.NetworkList.Internal.INetworkConnectionEvents\0Microsoft.Windows.NetworkList.Internal.INetworkListManagerEvents\0"), TypeLibType((short)2)]
internal class NetworkListManagerClass : INetworkListManager
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(7)]
public virtual extern ConnectivityStates GetConnectivity();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(2)]
public virtual extern INetwork GetNetwork([In] Guid gdNetworkId);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(4)]
public virtual extern INetworkConnection GetNetworkConnection([In] Guid gdNetworkConnectionId);
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(3)]
public virtual extern IEnumerable GetNetworkConnections();
[return: MarshalAs(UnmanagedType.Interface)]
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(1)]
public virtual extern IEnumerable GetNetworks([In] NetworkConnectivityLevels Flags);
[DispId(6)]
public virtual extern bool IsConnected
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(6)]
get;
}
[DispId(5)]
public virtual extern bool IsConnectedToInternet
{
[MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime), DispId(5)]
get;
}
}
}

Просмотреть файл

@ -0,0 +1,227 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
internal static class PowerManagementNativeMethods
{
#region Power Management
internal const uint PowerBroadcastMessage = 536;
internal const uint PowerSettingChangeMessage = 32787;
internal const uint ScreenSaverSetActive = 0x0011;
internal const uint UpdateInFile = 0x0001;
internal const uint SendChange = 0x0002;
// This structure is sent when the PBT_POWERSETTINGSCHANGE message is sent.
// It describes the power setting that has changed and
// contains data about the change.
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct PowerBroadcastSetting
{
public Guid PowerSetting;
public Int32 DataLength;
}
// This structure is used when calling CallNtPowerInformation
// to retrieve SystemPowerCapabilities
[StructLayout(LayoutKind.Sequential)]
public struct SystemPowerCapabilities
{
[MarshalAs(UnmanagedType.I1)]
public bool PowerButtonPresent;
[MarshalAs(UnmanagedType.I1)]
public bool SleepButtonPresent;
[MarshalAs(UnmanagedType.I1)]
public bool LidPresent;
[MarshalAs(UnmanagedType.I1)]
public bool SystemS1;
[MarshalAs(UnmanagedType.I1)]
public bool SystemS2;
[MarshalAs(UnmanagedType.I1)]
public bool SystemS3;
[MarshalAs(UnmanagedType.I1)]
public bool SystemS4;
[MarshalAs(UnmanagedType.I1)]
public bool SystemS5;
[MarshalAs(UnmanagedType.I1)]
public bool HiberFilePresent;
[MarshalAs(UnmanagedType.I1)]
public bool FullWake;
[MarshalAs(UnmanagedType.I1)]
public bool VideoDimPresent;
[MarshalAs(UnmanagedType.I1)]
public bool ApmPresent;
[MarshalAs(UnmanagedType.I1)]
public bool UpsPresent;
[MarshalAs(UnmanagedType.I1)]
public bool ThermalControl;
[MarshalAs(UnmanagedType.I1)]
public bool ProcessorThrottle;
public byte ProcessorMinimumThrottle;
public byte ProcessorMaximumThrottle;
[MarshalAs(UnmanagedType.I1)]
public bool FastSystemS4;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public byte[] spare2;
[MarshalAs(UnmanagedType.I1)]
public bool DiskSpinDown;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)]
public byte[] spare3;
[MarshalAs(UnmanagedType.I1)]
public bool SystemBatteriesPresent;
[MarshalAs(UnmanagedType.I1)]
public bool BatteriesAreShortTerm;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 3)]
public BatteryReportingScale[] BatteryScale;
public SystemPowerState AcOnlineWake;
public SystemPowerState SoftLidWake;
public SystemPowerState RtcWake;
public SystemPowerState MinimumDeviceWakeState;
public SystemPowerState DefaultLowLatencyWake;
}
public enum PowerInformationLevel
{
SystemPowerPolicyAc,
SystemPowerPolicyDc,
VerifySystemPolicyAc,
VerifySystemPolicyDc,
SystemPowerCapabilities,
SystemBatteryState,
SystemPowerStateHandler,
ProcessorStateHandler,
SystemPowerPolicyCurrent,
AdministratorPowerPolicy,
SystemReserveHiberFile,
ProcessorInformation,
SystemPowerInformation,
ProcessorStateHandler2,
LastWakeTime,
LastSleepTime,
SystemExecutionState,
SystemPowerStateNotifyHandler,
ProcessorPowerPolicyAc,
ProcessorPowerPolicyDc,
VerifyProcessorPowerPolicyAc,
VerifyProcessorPowerPolicyDc,
ProcessorPowerPolicyCurrent,
SystemPowerStateLogging,
SystemPowerLoggingEntry,
SetPowerSettingValue,
NotifyUserPowerSetting,
PowerInformationLevelUnused0,
PowerInformationLevelUnused1,
SystemVideoState,
TraceApplicationPowerMessage,
TraceApplicationPowerMessageEnd,
ProcessorPerfStates,
ProcessorIdleStates,
ProcessorCap,
SystemWakeSource,
SystemHiberFileInformation,
TraceServicePowerMessage,
ProcessorLoad,
PowerShutdownNotification,
MonitorCapabilities,
SessionPowerInit,
SessionDisplayState,
PowerRequestCreate,
PowerRequestAction,
GetPowerRequestList,
ProcessorInformationEx,
NotifyUserModeLegacyPowerEvent,
GroupPark,
ProcessorIdleDomains,
WakeTimerList,
SystemHiberFileSize,
PowerInformationLevelMaximum
}
[StructLayout(LayoutKind.Sequential)]
public struct BatteryReportingScale
{
public UInt32 Granularity;
public UInt32 Capacity;
}
public enum SystemPowerState
{
Unspecified = 0,
Working = 1,
Sleeping1 = 2,
Sleeping2 = 3,
Sleeping3 = 4,
Hibernate = 5,
Shutdown = 6,
Maximum = 7
}
[StructLayout(LayoutKind.Sequential)]
public struct SystemBatteryState
{
[MarshalAs(UnmanagedType.I1)]
public bool AcOnLine;
[MarshalAs(UnmanagedType.I1)]
public bool BatteryPresent;
[MarshalAs(UnmanagedType.I1)]
public bool Charging;
[MarshalAs(UnmanagedType.I1)]
public bool Discharging;
public byte Spare1;
public byte Spare2;
public byte Spare3;
public byte Spare4;
public uint MaxCapacity;
public uint RemainingCapacity;
public uint Rate;
public uint EstimatedTime;
public uint DefaultAlert1;
public uint DefaultAlert2;
}
[DllImport("powrprof.dll")]
internal static extern UInt32 CallNtPowerInformation(
PowerInformationLevel informationLevel,
IntPtr inputBuffer,
UInt32 inputBufferSize,
out SystemPowerCapabilities outputBuffer,
UInt32 outputBufferSize
);
[DllImport("powrprof.dll")]
internal static extern UInt32 CallNtPowerInformation(
PowerInformationLevel informationLevel,
IntPtr inputBuffer,
UInt32 inputBufferSize,
out SystemBatteryState outputBuffer,
UInt32 outputBufferSize
);
/// <summary>
/// Gets the Guid relating to the currently active power scheme.
/// </summary>
/// <param name="rootPowerKey">Reserved for future use, this must be set to IntPtr.Zero</param>
/// <param name="activePolicy">Returns a Guid referring to the currently active power scheme.</param>
[DllImport("powrprof.dll")]
internal static extern void PowerGetActiveScheme(
IntPtr rootPowerKey,
[MarshalAs(UnmanagedType.LPStruct)]
out Guid activePolicy);
[DllImport("User32", SetLastError = true,
EntryPoint = "RegisterPowerSettingNotification",
CallingConvention = CallingConvention.StdCall)]
internal static extern int RegisterPowerSettingNotification(
IntPtr hRecipient,
ref Guid PowerSettingGuid,
Int32 Flags);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern ExecutionStates SetThreadExecutionState(ExecutionStates esFlags);
#endregion
}
}

Просмотреть файл

@ -0,0 +1,612 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Resources;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Encapsulates the native logic required to create,
/// configure, and show a TaskDialog,
/// via the TaskDialogIndirect() Win32 function.
/// </summary>
/// <remarks>A new instance of this class should
/// be created for each messagebox show, as
/// the HWNDs for TaskDialogs do not remain constant
/// across calls to TaskDialogIndirect.
/// </remarks>
internal class NativeTaskDialog : IDisposable
{
private TaskDialogNativeMethods.TaskDialogConfiguration nativeDialogConfig;
private NativeTaskDialogSettings settings;
private IntPtr hWndDialog;
private TaskDialog outerDialog;
private IntPtr[] updatedStrings = new IntPtr[Enum.GetNames(typeof(TaskDialogNativeMethods.TaskDialogElements)).Length];
private IntPtr buttonArray, radioButtonArray;
// Flag tracks whether our first radio
// button click event has come through.
private bool firstRadioButtonClicked = true;
#region Constructors
// Configuration is applied at dialog creation time.
internal NativeTaskDialog(NativeTaskDialogSettings settings, TaskDialog outerDialog)
{
nativeDialogConfig = settings.NativeConfiguration;
this.settings = settings;
// Wireup dialog proc message loop for this instance.
nativeDialogConfig.callback = new TaskDialogNativeMethods.TaskDialogCallback(DialogProc);
ShowState = DialogShowState.PreShow;
// Keep a reference to the outer shell, so we can notify.
this.outerDialog = outerDialog;
}
#endregion
#region Public Properties
public DialogShowState ShowState { get; private set; }
public int SelectedButtonId { get; private set; }
public int SelectedRadioButtonId { get; private set; }
public bool CheckBoxChecked { get; private set; }
#endregion
internal void NativeShow()
{
// Applies config struct and other settings, then
// calls main Win32 function.
if (settings == null)
{
throw new InvalidOperationException(LocalizedMessages.NativeTaskDialogConfigurationError);
}
// Do a last-minute parse of the various dialog control lists,
// and only allocate the memory at the last minute.
MarshalDialogControlStructs();
// Make the call and show the dialog.
// NOTE: this call is BLOCKING, though the thread
// WILL re-enter via the DialogProc.
try
{
ShowState = DialogShowState.Showing;
int selectedButtonId;
int selectedRadioButtonId;
bool checkBoxChecked;
// Here is the way we use "vanilla" P/Invoke to call TaskDialogIndirect().
HResult hresult = TaskDialogNativeMethods.TaskDialogIndirect(
nativeDialogConfig,
out selectedButtonId,
out selectedRadioButtonId,
out checkBoxChecked);
if (CoreErrorHelper.Failed(hresult))
{
string msg;
switch (hresult)
{
case HResult.InvalidArguments:
msg = LocalizedMessages.NativeTaskDialogInternalErrorArgs;
break;
case HResult.OutOfMemory:
msg = LocalizedMessages.NativeTaskDialogInternalErrorComplex;
break;
default:
msg = string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.NativeTaskDialogInternalErrorUnexpected,
hresult);
break;
}
Exception e = Marshal.GetExceptionForHR((int)hresult);
throw new Win32Exception(msg, e);
}
SelectedButtonId = selectedButtonId;
SelectedRadioButtonId = selectedRadioButtonId;
CheckBoxChecked = checkBoxChecked;
}
catch (EntryPointNotFoundException exc)
{
throw new NotSupportedException(LocalizedMessages.NativeTaskDialogVersionError, exc);
}
finally
{
ShowState = DialogShowState.Closed;
}
}
// The new task dialog does not support the existing
// Win32 functions for closing (e.g. EndDialog()); instead,
// a "click button" message is sent. In this case, we're
// abstracting out to say that the TaskDialog consumer can
// simply call "Close" and we'll "click" the cancel button.
// Note that the cancel button doesn't actually
// have to exist for this to work.
internal void NativeClose(TaskDialogResult result)
{
ShowState = DialogShowState.Closing;
int id;
switch (result)
{
case TaskDialogResult.Close:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Close;
break;
case TaskDialogResult.CustomButtonClicked:
id = DialogsDefaults.MinimumDialogControlId; // custom buttons
break;
case TaskDialogResult.No:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.No;
break;
case TaskDialogResult.Ok:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Ok;
break;
case TaskDialogResult.Retry:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Retry;
break;
case TaskDialogResult.Yes:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Yes;
break;
default:
id = (int)TaskDialogNativeMethods.TaskDialogCommonButtonReturnIds.Cancel;
break;
}
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.ClickButton, id, 0);
}
#region Main Dialog Proc
private int DialogProc(
IntPtr windowHandle,
uint message,
IntPtr wparam,
IntPtr lparam,
IntPtr referenceData)
{
// Fetch the HWND - it may be the first time we're getting it.
hWndDialog = windowHandle;
// Big switch on the various notifications the
// dialog proc can get.
switch ((TaskDialogNativeMethods.TaskDialogNotifications)message)
{
case TaskDialogNativeMethods.TaskDialogNotifications.Created:
int result = PerformDialogInitialization();
outerDialog.RaiseOpenedEvent();
return result;
case TaskDialogNativeMethods.TaskDialogNotifications.ButtonClicked:
return HandleButtonClick((int)wparam);
case TaskDialogNativeMethods.TaskDialogNotifications.RadioButtonClicked:
return HandleRadioButtonClick((int)wparam);
case TaskDialogNativeMethods.TaskDialogNotifications.HyperlinkClicked:
return HandleHyperlinkClick(lparam);
case TaskDialogNativeMethods.TaskDialogNotifications.Help:
return HandleHelpInvocation();
case TaskDialogNativeMethods.TaskDialogNotifications.Timer:
return HandleTick((int)wparam);
case TaskDialogNativeMethods.TaskDialogNotifications.Destroyed:
return PerformDialogCleanup();
default:
break;
}
return (int)HResult.Ok;
}
// Once the task dialog HWND is open, we need to send
// additional messages to configure it.
private int PerformDialogInitialization()
{
// Initialize Progress or Marquee Bar.
if (IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.ShowProgressBar))
{
UpdateProgressBarRange();
// The order of the following is important -
// state is more important than value,
// and non-normal states turn off the bar value change
// animation, which is likely the intended
// and preferable behavior.
UpdateProgressBarState(settings.ProgressBarState);
UpdateProgressBarValue(settings.ProgressBarValue);
// Due to a bug that wasn't fixed in time for RTM of Vista,
// second SendMessage is required if the state is non-Normal.
UpdateProgressBarValue(settings.ProgressBarValue);
}
else if (IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.ShowMarqueeProgressBar))
{
// TDM_SET_PROGRESS_BAR_MARQUEE is necessary
// to cause the marquee to start animating.
// Note that this internal task dialog setting is
// round-tripped when the marquee is
// is set to different states, so it never has to
// be touched/sent again.
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarMarquee, 1, 0);
UpdateProgressBarState(settings.ProgressBarState);
}
if (settings.ElevatedButtons != null && settings.ElevatedButtons.Count > 0)
{
foreach (int id in settings.ElevatedButtons)
{
UpdateElevationIcon(id, true);
}
}
return CoreErrorHelper.Ignored;
}
private int HandleButtonClick(int id)
{
// First we raise a Click event, if there is a custom button
// However, we implement Close() by sending a cancel button, so
// we don't want to raise a click event in response to that.
if (ShowState != DialogShowState.Closing)
{
outerDialog.RaiseButtonClickEvent(id);
}
// Once that returns, we raise a Closing event for the dialog
// The Win32 API handles button clicking-and-closing
// as an atomic action,
// but it is more .NET friendly to split them up.
// Unfortunately, we do NOT have the return values at this stage.
if (id < DialogsDefaults.MinimumDialogControlId)
{
return outerDialog.RaiseClosingEvent(id);
}
return (int)HResult.False;
}
private int HandleRadioButtonClick(int id)
{
// When the dialog sets the radio button to default,
// it (somewhat confusingly)issues a radio button clicked event
// - we mask that out - though ONLY if
// we do have a default radio button
if (firstRadioButtonClicked
&& !IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions.NoDefaultRadioButton))
{
firstRadioButtonClicked = false;
}
else
{
outerDialog.RaiseButtonClickEvent(id);
}
// Note: we don't raise Closing, as radio
// buttons are non-committing buttons
return CoreErrorHelper.Ignored;
}
private int HandleHyperlinkClick(IntPtr href)
{
string link = Marshal.PtrToStringUni(href);
outerDialog.RaiseHyperlinkClickEvent(link);
return CoreErrorHelper.Ignored;
}
private int HandleTick(int ticks)
{
outerDialog.RaiseTickEvent(ticks);
return CoreErrorHelper.Ignored;
}
private int HandleHelpInvocation()
{
outerDialog.RaiseHelpInvokedEvent();
return CoreErrorHelper.Ignored;
}
// There should be little we need to do here,
// as the use of the NativeTaskDialog is
// that it is instantiated for a single show, then disposed of.
private int PerformDialogCleanup()
{
firstRadioButtonClicked = true;
return CoreErrorHelper.Ignored;
}
#endregion
#region Update members
internal void UpdateProgressBarValue(int i)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarPosition, i, 0);
}
internal void UpdateProgressBarRange()
{
AssertCurrentlyShowing();
// Build range LPARAM - note it is in REVERSE intuitive order.
long range = NativeTaskDialog.MakeLongLParam(
settings.ProgressBarMaximum,
settings.ProgressBarMinimum);
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarRange, 0, range);
}
internal void UpdateProgressBarState(TaskDialogProgressBarState state)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.SetProgressBarState, (int)state, 0);
}
internal void UpdateText(string text)
{
UpdateTextCore(text, TaskDialogNativeMethods.TaskDialogElements.Content);
}
internal void UpdateInstruction(string instruction)
{
UpdateTextCore(instruction, TaskDialogNativeMethods.TaskDialogElements.MainInstruction);
}
internal void UpdateFooterText(string footerText)
{
UpdateTextCore(footerText, TaskDialogNativeMethods.TaskDialogElements.Footer);
}
internal void UpdateExpandedText(string expandedText)
{
UpdateTextCore(expandedText, TaskDialogNativeMethods.TaskDialogElements.ExpandedInformation);
}
private void UpdateTextCore(string s, TaskDialogNativeMethods.TaskDialogElements element)
{
AssertCurrentlyShowing();
FreeOldString(element);
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.SetElementText,
(int)element,
(long)MakeNewString(s, element));
}
internal void UpdateMainIcon(TaskDialogStandardIcon mainIcon)
{
UpdateIconCore(mainIcon, TaskDialogNativeMethods.TaskDialogIconElement.Main);
}
internal void UpdateFooterIcon(TaskDialogStandardIcon footerIcon)
{
UpdateIconCore(footerIcon, TaskDialogNativeMethods.TaskDialogIconElement.Footer);
}
private void UpdateIconCore(TaskDialogStandardIcon icon, TaskDialogNativeMethods.TaskDialogIconElement element)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.UpdateIcon,
(int)element,
(long)icon);
}
internal void UpdateCheckBoxChecked(bool cbc)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.ClickVerification,
(cbc ? 1 : 0),
1);
}
internal void UpdateElevationIcon(int buttonId, bool showIcon)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.SetButtonElevationRequiredState,
buttonId,
Convert.ToInt32(showIcon));
}
internal void UpdateButtonEnabled(int buttonID, bool enabled)
{
AssertCurrentlyShowing();
SendMessageHelper(
TaskDialogNativeMethods.TaskDialogMessages.EnableButton, buttonID, enabled == true ? 1 : 0);
}
internal void UpdateRadioButtonEnabled(int buttonID, bool enabled)
{
AssertCurrentlyShowing();
SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages.EnableRadioButton,
buttonID, enabled == true ? 1 : 0);
}
internal void AssertCurrentlyShowing()
{
Debug.Assert(ShowState == DialogShowState.Showing,
"Update*() methods should only be called while native dialog is showing");
}
#endregion
#region Helpers
private int SendMessageHelper(TaskDialogNativeMethods.TaskDialogMessages message, int wparam, long lparam)
{
// Be sure to at least assert here -
// messages to invalid handles often just disappear silently
Debug.Assert(hWndDialog != null, "HWND for dialog is null during SendMessage");
return (int)CoreNativeMethods.SendMessage(
hWndDialog,
(uint)message,
(IntPtr)wparam,
new IntPtr(lparam));
}
private bool IsOptionSet(TaskDialogNativeMethods.TaskDialogOptions flag)
{
return ((nativeDialogConfig.taskDialogFlags & flag) == flag);
}
// Allocates a new string on the unmanaged heap,
// and stores the pointer so we can free it later.
private IntPtr MakeNewString(string text, TaskDialogNativeMethods.TaskDialogElements element)
{
IntPtr newStringPtr = Marshal.StringToHGlobalUni(text);
updatedStrings[(int)element] = newStringPtr;
return newStringPtr;
}
// Checks to see if the given element already has an
// updated string, and if so,
// frees it. This is done in preparation for a call to
// MakeNewString(), to prevent
// leaks from multiple updates calls on the same element
// within a single native dialog lifetime.
private void FreeOldString(TaskDialogNativeMethods.TaskDialogElements element)
{
int elementIndex = (int)element;
if (updatedStrings[elementIndex] != IntPtr.Zero)
{
Marshal.FreeHGlobal(updatedStrings[elementIndex]);
updatedStrings[elementIndex] = IntPtr.Zero;
}
}
// Based on the following defines in WinDef.h and WinUser.h:
// #define MAKELPARAM(l, h) ((LPARAM)(DWORD)MAKELONG(l, h))
// #define MAKELONG(a, b) ((LONG)(((WORD)(((DWORD_PTR)(a)) & 0xffff)) | ((DWORD)((WORD)(((DWORD_PTR)(b)) & 0xffff))) << 16))
private static long MakeLongLParam(int a, int b)
{
return (a << 16) + b;
}
// Builds the actual configuration that the
// NativeTaskDialog (and underlying Win32 API)
// expects, by parsing the various control lists,
// marshaling to the unmanaged heap, etc.
private void MarshalDialogControlStructs()
{
if (settings.Buttons != null && settings.Buttons.Length > 0)
{
buttonArray = AllocateAndMarshalButtons(settings.Buttons);
settings.NativeConfiguration.buttons = buttonArray;
settings.NativeConfiguration.buttonCount = (uint)settings.Buttons.Length;
}
if (settings.RadioButtons != null && settings.RadioButtons.Length > 0)
{
radioButtonArray = AllocateAndMarshalButtons(settings.RadioButtons);
settings.NativeConfiguration.radioButtons = radioButtonArray;
settings.NativeConfiguration.radioButtonCount = (uint)settings.RadioButtons.Length;
}
}
private static IntPtr AllocateAndMarshalButtons(TaskDialogNativeMethods.TaskDialogButton[] structs)
{
IntPtr initialPtr = Marshal.AllocHGlobal(
Marshal.SizeOf(typeof(TaskDialogNativeMethods.TaskDialogButton)) * structs.Length);
IntPtr currentPtr = initialPtr;
foreach (TaskDialogNativeMethods.TaskDialogButton button in structs)
{
Marshal.StructureToPtr(button, currentPtr, false);
currentPtr = (IntPtr)((int)currentPtr + Marshal.SizeOf(button));
}
return initialPtr;
}
#endregion
#region IDispose Pattern
private bool disposed;
// Finalizer and IDisposable implementation.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~NativeTaskDialog()
{
Dispose(false);
}
// Core disposing logic.
protected void Dispose(bool disposing)
{
if (!disposed)
{
disposed = true;
// Single biggest resource - make sure the dialog
// itself has been instructed to close.
if (ShowState == DialogShowState.Showing)
{
NativeClose(TaskDialogResult.Cancel);
}
// Clean up custom allocated strings that were updated
// while the dialog was showing. Note that the strings
// passed in the initial TaskDialogIndirect call will
// be cleaned up automagically by the default
// marshalling logic.
if (updatedStrings != null)
{
for (int i = 0; i < updatedStrings.Length; i++)
{
if (updatedStrings[i] != IntPtr.Zero)
{
Marshal.FreeHGlobal(updatedStrings[i]);
updatedStrings[i] = IntPtr.Zero;
}
}
}
// Clean up the button and radio button arrays, if any.
if (buttonArray != IntPtr.Zero)
{
Marshal.FreeHGlobal(buttonArray);
buttonArray = IntPtr.Zero;
}
if (radioButtonArray != IntPtr.Zero)
{
Marshal.FreeHGlobal(radioButtonArray);
radioButtonArray = IntPtr.Zero;
}
if (disposing)
{
// Clean up managed resources - currently there are none
// that are interesting.
}
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,58 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
///<summary>
/// Encapsulates additional configuration needed by NativeTaskDialog
/// that it can't get from the TASKDIALOGCONFIG struct.
///</summary>
internal class NativeTaskDialogSettings
{
internal NativeTaskDialogSettings()
{
NativeConfiguration = new TaskDialogNativeMethods.TaskDialogConfiguration();
// Apply standard settings.
NativeConfiguration.size = (uint)Marshal.SizeOf(NativeConfiguration);
NativeConfiguration.parentHandle = IntPtr.Zero;
NativeConfiguration.instance = IntPtr.Zero;
NativeConfiguration.taskDialogFlags = TaskDialogNativeMethods.TaskDialogOptions.AllowCancel;
NativeConfiguration.commonButtons = TaskDialogNativeMethods.TaskDialogCommonButtons.Ok;
NativeConfiguration.mainIcon = new TaskDialogNativeMethods.IconUnion(0);
NativeConfiguration.footerIcon = new TaskDialogNativeMethods.IconUnion(0);
NativeConfiguration.width = TaskDialogDefaults.IdealWidth;
// Zero out all the custom button fields.
NativeConfiguration.buttonCount = 0;
NativeConfiguration.radioButtonCount = 0;
NativeConfiguration.buttons = IntPtr.Zero;
NativeConfiguration.radioButtons = IntPtr.Zero;
NativeConfiguration.defaultButtonIndex = 0;
NativeConfiguration.defaultRadioButtonIndex = 0;
// Various text defaults.
NativeConfiguration.windowTitle = TaskDialogDefaults.Caption;
NativeConfiguration.mainInstruction = TaskDialogDefaults.MainInstruction;
NativeConfiguration.content = TaskDialogDefaults.Content;
NativeConfiguration.verificationText = null;
NativeConfiguration.expandedInformation = null;
NativeConfiguration.expandedControlText = null;
NativeConfiguration.collapsedControlText = null;
NativeConfiguration.footerText = null;
}
public int ProgressBarMinimum { get; set; }
public int ProgressBarMaximum { get; set; }
public int ProgressBarValue { get; set; }
public TaskDialogProgressBarState ProgressBarState { get; set; }
public bool InvokeHelp { get; set; }
public TaskDialogNativeMethods.TaskDialogConfiguration NativeConfiguration { get; private set; }
public TaskDialogNativeMethods.TaskDialogButton[] Buttons { get; set; }
public TaskDialogNativeMethods.TaskDialogButton[] RadioButtons { get; set; }
public List<int> ElevatedButtons { get; set; }
}
}

Просмотреть файл

@ -0,0 +1,233 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Dialogs
{
/// <summary>
/// Internal class containing most native interop declarations used
/// throughout the library.
/// Functions that are not performance intensive belong in this class.
/// </summary>
internal static class TaskDialogNativeMethods
{
#region TaskDialog Definitions
[DllImport("Comctl32.dll", SetLastError = true)]
internal static extern HResult TaskDialogIndirect(
[In] TaskDialogNativeMethods.TaskDialogConfiguration taskConfig,
[Out] out int button,
[Out] out int radioButton,
[MarshalAs(UnmanagedType.Bool), Out] out bool verificationFlagChecked);
// Main task dialog configuration struct.
// NOTE: Packing must be set to 4 to make this work on 64-bit platforms.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
internal class TaskDialogConfiguration
{
internal uint size;
internal IntPtr parentHandle;
internal IntPtr instance;
internal TaskDialogOptions taskDialogFlags;
internal TaskDialogCommonButtons commonButtons;
[MarshalAs(UnmanagedType.LPWStr)]
internal string windowTitle;
internal IconUnion mainIcon; // NOTE: 32-bit union field, holds pszMainIcon as well
[MarshalAs(UnmanagedType.LPWStr)]
internal string mainInstruction;
[MarshalAs(UnmanagedType.LPWStr)]
internal string content;
internal uint buttonCount;
internal IntPtr buttons; // Ptr to TASKDIALOG_BUTTON structs
internal int defaultButtonIndex;
internal uint radioButtonCount;
internal IntPtr radioButtons; // Ptr to TASKDIALOG_BUTTON structs
internal int defaultRadioButtonIndex;
[MarshalAs(UnmanagedType.LPWStr)]
internal string verificationText;
[MarshalAs(UnmanagedType.LPWStr)]
internal string expandedInformation;
[MarshalAs(UnmanagedType.LPWStr)]
internal string expandedControlText;
[MarshalAs(UnmanagedType.LPWStr)]
internal string collapsedControlText;
internal IconUnion footerIcon; // NOTE: 32-bit union field, holds pszFooterIcon as well
[MarshalAs(UnmanagedType.LPWStr)]
internal string footerText;
internal TaskDialogCallback callback;
internal IntPtr callbackData;
internal uint width;
}
internal const int TaskDialogIdealWidth = 0; // Value for TASKDIALOGCONFIG.cxWidth
internal const int TaskDialogButtonShieldIcon = 1;
// NOTE: We include a "spacer" so that the struct size varies on
// 64-bit architectures.
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
internal struct IconUnion
{
internal IconUnion(int i)
{
mainIcon = i;
spacer = IntPtr.Zero;
}
[FieldOffset(0)]
private int mainIcon;
// This field is used to adjust the length of the structure on 32/64bit OS.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1823:AvoidUnusedPrivateFields")]
[FieldOffset(0)]
private IntPtr spacer;
/// <summary>
/// Gets the handle to the Icon
/// </summary>
public int MainIcon { get { return mainIcon; } }
}
// NOTE: Packing must be set to 4 to make this work on 64-bit platforms.
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
internal struct TaskDialogButton
{
public TaskDialogButton(int buttonId, string text)
{
this.buttonId = buttonId;
buttonText = text;
}
internal int buttonId;
[MarshalAs(UnmanagedType.LPWStr)]
internal string buttonText;
}
// Task Dialog - identifies common buttons.
[Flags]
internal enum TaskDialogCommonButtons
{
Ok = 0x0001, // selected control return value IDOK
Yes = 0x0002, // selected control return value IDYES
No = 0x0004, // selected control return value IDNO
Cancel = 0x0008, // selected control return value IDCANCEL
Retry = 0x0010, // selected control return value IDRETRY
Close = 0x0020 // selected control return value IDCLOSE
}
// Identify button *return values* - note that, unfortunately, these are different
// from the inbound button values.
internal enum TaskDialogCommonButtonReturnIds
{
Ok = 1,
Cancel = 2,
Abort = 3,
Retry = 4,
Ignore = 5,
Yes = 6,
No = 7,
Close = 8
}
internal enum TaskDialogElements
{
Content,
ExpandedInformation,
Footer,
MainInstruction
}
internal enum TaskDialogIconElement
{
Main,
Footer
}
// Task Dialog - flags
[Flags]
internal enum TaskDialogOptions
{
None = 0,
EnableHyperlinks = 0x0001,
UseMainIcon = 0x0002,
UseFooterIcon = 0x0004,
AllowCancel = 0x0008,
UseCommandLinks = 0x0010,
UseNoIconCommandLinks = 0x0020,
ExpandFooterArea = 0x0040,
ExpandedByDefault = 0x0080,
CheckVerificationFlag = 0x0100,
ShowProgressBar = 0x0200,
ShowMarqueeProgressBar = 0x0400,
UseCallbackTimer = 0x0800,
PositionRelativeToWindow = 0x1000,
RightToLeftLayout = 0x2000,
NoDefaultRadioButton = 0x4000
}
internal enum TaskDialogMessages
{
NavigatePage = CoreNativeMethods.UserMessage + 101,
ClickButton = CoreNativeMethods.UserMessage + 102, // wParam = Button ID
SetMarqueeProgressBar = CoreNativeMethods.UserMessage + 103, // wParam = 0 (nonMarque) wParam != 0 (Marquee)
SetProgressBarState = CoreNativeMethods.UserMessage + 104, // wParam = new progress state
SetProgressBarRange = CoreNativeMethods.UserMessage + 105, // lParam = MAKELPARAM(nMinRange, nMaxRange)
SetProgressBarPosition = CoreNativeMethods.UserMessage + 106, // wParam = new position
SetProgressBarMarquee = CoreNativeMethods.UserMessage + 107, // wParam = 0 (stop marquee), wParam != 0 (start marquee), lparam = speed (milliseconds between repaints)
SetElementText = CoreNativeMethods.UserMessage + 108, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
ClickRadioButton = CoreNativeMethods.UserMessage + 110, // wParam = Radio Button ID
EnableButton = CoreNativeMethods.UserMessage + 111, // lParam = 0 (disable), lParam != 0 (enable), wParam = Button ID
EnableRadioButton = CoreNativeMethods.UserMessage + 112, // lParam = 0 (disable), lParam != 0 (enable), wParam = Radio Button ID
ClickVerification = CoreNativeMethods.UserMessage + 113, // wParam = 0 (unchecked), 1 (checked), lParam = 1 (set key focus)
UpdateElementText = CoreNativeMethods.UserMessage + 114, // wParam = element (TASKDIALOG_ELEMENTS), lParam = new element text (LPCWSTR)
SetButtonElevationRequiredState = CoreNativeMethods.UserMessage + 115, // wParam = Button ID, lParam = 0 (elevation not required), lParam != 0 (elevation required)
UpdateIcon = CoreNativeMethods.UserMessage + 116 // wParam = icon element (TASKDIALOG_ICON_ELEMENTS), lParam = new icon (hIcon if TDF_USE_HICON_* was set, PCWSTR otherwise)
}
internal enum TaskDialogNotifications
{
Created = 0,
Navigated = 1,
ButtonClicked = 2, // wParam = Button ID
HyperlinkClicked = 3, // lParam = (LPCWSTR)pszHREF
Timer = 4, // wParam = Milliseconds since dialog created or timer reset
Destroyed = 5,
RadioButtonClicked = 6, // wParam = Radio Button ID
Constructed = 7,
VerificationClicked = 8, // wParam = 1 if checkbox checked, 0 if not, lParam is unused and always 0
Help = 9,
ExpandButtonClicked = 10 // wParam = 0 (dialog is now collapsed), wParam != 0 (dialog is now expanded)
}
// Used in the various SET_DEFAULT* TaskDialog messages
internal const int NoDefaultButtonSpecified = 0;
// Task Dialog config and related structs (for TaskDialogIndirect())
internal delegate int TaskDialogCallback(
IntPtr hwnd,
uint message,
IntPtr wparam,
IntPtr lparam,
IntPtr referenceData);
internal enum ProgressBarState
{
Normal = 0x0001,
Error = 0x0002,
Paused = 0x0003
}
internal enum TaskDialogIcons
{
Warning = 65535,
Error = 65534,
Information = 65533,
Shield = 65532
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,234 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MS.WindowsAPICodePack.Internal
{
internal enum WindowMessage
{
Null = 0x00,
Create = 0x01,
Destroy = 0x02,
Move = 0x03,
Size = 0x05,
Activate = 0x06,
SetFocus = 0x07,
KillFocus = 0x08,
Enable = 0x0A,
SetRedraw = 0x0B,
SetText = 0x0C,
GetText = 0x0D,
GetTextLength = 0x0E,
Paint = 0x0F,
Close = 0x10,
QueryEndSession = 0x11,
Quit = 0x12,
QueryOpen = 0x13,
EraseBackground = 0x14,
SystemColorChange = 0x15,
EndSession = 0x16,
SystemError = 0x17,
ShowWindow = 0x18,
ControlColor = 0x19,
WinIniChange = 0x1A,
SettingChange = 0x1A,
DevModeChange = 0x1B,
ActivateApplication = 0x1C,
FontChange = 0x1D,
TimeChange = 0x1E,
CancelMode = 0x1F,
SetCursor = 0x20,
MouseActivate = 0x21,
ChildActivate = 0x22,
QueueSync = 0x23,
GetMinMaxInfo = 0x24,
PaintIcon = 0x26,
IconEraseBackground = 0x27,
NextDialogControl = 0x28,
SpoolerStatus = 0x2A,
DrawItem = 0x2B,
MeasureItem = 0x2C,
DeleteItem = 0x2D,
VKeyToItem = 0x2E,
CharToItem = 0x2F,
SetFont = 0x30,
GetFont = 0x31,
SetHotkey = 0x32,
GetHotkey = 0x33,
QueryDragIcon = 0x37,
CompareItem = 0x39,
Compacting = 0x41,
WindowPositionChanging = 0x46,
WindowPositionChanged = 0x47,
Power = 0x48,
CopyData = 0x4A,
CancelJournal = 0x4B,
Notify = 0x4E,
InputLanguageChangeRequest = 0x50,
InputLanguageChange = 0x51,
TCard = 0x52,
Help = 0x53,
UserChanged = 0x54,
NotifyFormat = 0x55,
ContextMenu = 0x7B,
StyleChanging = 0x7C,
StyleChanged = 0x7D,
DisplayChange = 0x7E,
GetIcon = 0x7F,
SetIcon = 0x80,
NCCreate = 0x81,
NCDestroy = 0x82,
NCCalculateSize = 0x83,
NCHitTest = 0x84,
NCPaint = 0x85,
NCActivate = 0x86,
GetDialogCode = 0x87,
NCMouseMove = 0xA0,
NCLeftButtonDown = 0xA1,
NCLeftButtonUp = 0xA2,
NCLeftButtonDoubleClick = 0xA3,
NCRightButtonDown = 0xA4,
NCRightButtonUp = 0xA5,
NCRightButtonDoubleClick = 0xA6,
NCMiddleButtonDown = 0xA7,
NCMiddleButtonUp = 0xA8,
NCMiddleButtonDoubleClick = 0xA9,
KeyFirst = 0x100,
KeyDown = 0x100,
KeyUp = 0x101,
Char = 0x102,
DeadChar = 0x103,
SystemKeyDown = 0x104,
SystemKeyUp = 0x105,
SystemChar = 0x106,
SystemDeadChar = 0x107,
KeyLast = 0x108,
IMEStartComposition = 0x10D,
IMEEndComposition = 0x10E,
IMEComposition = 0x10F,
IMEKeyLast = 0x10F,
InitializeDialog = 0x110,
Command = 0x111,
SystemCommand = 0x112,
Timer = 0x113,
HorizontalScroll = 0x114,
VerticalScroll = 0x115,
InitializeMenu = 0x116,
InitializeMenuPopup = 0x117,
MenuSelect = 0x11F,
MenuChar = 0x120,
EnterIdle = 0x121,
CTLColorMessageBox = 0x132,
CTLColorEdit = 0x133,
CTLColorListbox = 0x134,
CTLColorButton = 0x135,
CTLColorDialog = 0x136,
CTLColorScrollBar = 0x137,
CTLColorStatic = 0x138,
MouseFirst = 0x200,
MouseMove = 0x200,
LeftButtonDown = 0x201,
LeftButtonUp = 0x202,
LeftButtonDoubleClick = 0x203,
RightButtonDown = 0x204,
RightButtonUp = 0x205,
RightButtonDoubleClick = 0x206,
MiddleButtonDown = 0x207,
MiddleButtonUp = 0x208,
MiddleButtonDoubleClick = 0x209,
MouseWheel = 0x20A,
MouseHorizontalWheel = 0x20E,
ParentNotify = 0x210,
EnterMenuLoop = 0x211,
ExitMenuLoop = 0x212,
NextMenu = 0x213,
Sizing = 0x214,
CaptureChanged = 0x215,
Moving = 0x216,
PowerBroadcast = 0x218,
DeviceChange = 0x219,
MDICreate = 0x220,
MDIDestroy = 0x221,
MDIActivate = 0x222,
MDIRestore = 0x223,
MDINext = 0x224,
MDIMaximize = 0x225,
MDITile = 0x226,
MDICascade = 0x227,
MDIIconArrange = 0x228,
MDIGetActive = 0x229,
MDISetMenu = 0x230,
EnterSizeMove = 0x231,
ExitSizeMove = 0x232,
DropFiles = 0x233,
MDIRefreshMenu = 0x234,
IMESetContext = 0x281,
IMENotify = 0x282,
IMEControl = 0x283,
IMECompositionFull = 0x284,
IMESelect = 0x285,
IMEChar = 0x286,
IMEKeyDown = 0x290,
IMEKeyUp = 0x291,
MouseHover = 0x2A1,
NCMouseLeave = 0x2A2,
MouseLeave = 0x2A3,
Cut = 0x300,
Copy = 0x301,
Paste = 0x302,
Clear = 0x303,
Undo = 0x304,
RenderFormat = 0x305,
RenderAllFormats = 0x306,
DestroyClipboard = 0x307,
DrawClipbard = 0x308,
PaintClipbard = 0x309,
VerticalScrollClipBoard = 0x30A,
SizeClipbard = 0x30B,
AskClipboardFormatname = 0x30C,
ChangeClipboardChain = 0x30D,
HorizontalScrollClipboard = 0x30E,
QueryNewPalette = 0x30F,
PaletteIsChanging = 0x310,
PaletteChanged = 0x311,
Hotkey = 0x312,
Print = 0x317,
PrintClient = 0x318,
HandHeldFirst = 0x358,
HandHeldlast = 0x35F,
PenWinFirst = 0x380,
PenWinLast = 0x38F,
CoalesceFirst = 0x390,
CoalesceLast = 0x39F,
DDE_First = 0x3E0,
DDE_Initiate = 0x3E0,
DDE_Terminate = 0x3E1,
DDE_Advise = 0x3E2,
DDE_Unadvise = 0x3E3,
DDE_Ack = 0x3E4,
DDE_Data = 0x3E5,
DDE_Request = 0x3E6,
DDE_Poke = 0x3E7,
DDE_Execute = 0x3E8,
DDE_Last = 0x3E8,
User = 0x400,
App = 0x8000,
}
}

5
Core/Makefile.am Normal file
Просмотреть файл

@ -0,0 +1,5 @@
include $(top_srcdir)/xbuild.include
if ! ENABLE_WINDOWSPLATFORM
SKIP=y
endif

201
Core/NetworkList/Network.cs Normal file
Просмотреть файл

@ -0,0 +1,201 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Net
{
/// <summary>
/// Represents a network on the local machine.
/// It can also represent a collection of network
/// connections with a similar network signature.
/// </summary>
/// <remarks>
/// Instances of this class are obtained by calling
/// methods on the <see cref="NetworkListManager"/> class.
/// </remarks>
public class Network
{
#region Private Fields
INetwork network;
#endregion // Private Fields
internal Network(INetwork network)
{
this.network = network;
}
/// <summary>
/// Gets or sets the category of a network. The
/// categories are trusted, untrusted, or
/// authenticated.
/// </summary>
/// <value>A <see cref="NetworkCategory"/> value.</value>
public NetworkCategory Category
{
get
{
return network.GetCategory();
}
set
{
network.SetCategory(value);
}
}
/// <summary>
/// Gets the local date and time when the network
/// was connected.
/// </summary>
/// <value>A <see cref="System.DateTime"/> object.</value>
public DateTime ConnectedTime
{
get
{
uint low, high, dummy1, dummy2;
network.GetTimeCreatedAndConnected(out dummy1, out dummy2, out low, out high);
long time = high;
// Shift the day info into the high order bits.
time <<= 32;
time |= low;
return DateTime.FromFileTimeUtc(time);
}
}
/// <summary>
/// Gets the network connections for the network.
/// </summary>
/// <value>A <see cref="NetworkConnectionCollection"/> object.</value>
public NetworkConnectionCollection Connections
{
get
{
return new NetworkConnectionCollection(network.GetNetworkConnections());
}
}
/// <summary>
/// Gets the connectivity state of the network.
/// </summary>
/// <value>A <see cref="Connectivity"/> value.</value>
/// <remarks>Connectivity provides information on whether
/// the network is connected, and the protocols
/// in use for network traffic.</remarks>
public ConnectivityStates Connectivity
{
get
{
return network.GetConnectivity();
}
}
/// <summary>
/// Gets the local date and time when the
/// network was created.
/// </summary>
/// <value>A <see cref="System.DateTime"/> object.</value>
public DateTime CreatedTime
{
get
{
uint low, high, dummy1, dummy2;
network.GetTimeCreatedAndConnected(out low, out high, out dummy1, out dummy2);
long time = high;
//Shift the value into the high order bits.
time <<= 32;
time |= low;
return DateTime.FromFileTimeUtc(time);
}
}
/// <summary>
/// Gets or sets a description for the network.
/// </summary>
/// <value>A <see cref="System.String"/> value.</value>
public string Description
{
get
{
return network.GetDescription();
}
set
{
network.SetDescription(value);
}
}
/// <summary>
/// Gets the domain type of the network.
/// </summary>
/// <value>A <see cref="DomainType"/> value.</value>
/// <remarks>The domain
/// indictates whether the network is an Active
/// Directory Network, and whether the machine
/// has been authenticated by Active Directory.</remarks>
public DomainType DomainType
{
get
{
return network.GetDomainType();
}
}
/// <summary>
/// Gets a value that indicates whether there is
/// network connectivity.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
public bool IsConnected
{
get
{
return network.IsConnected;
}
}
/// <summary>
/// Gets a value that indicates whether there is
/// Internet connectivity.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
public bool IsConnectedToInternet
{
get
{
return network.IsConnectedToInternet;
}
}
/// <summary>
/// Gets or sets the name of the network.
/// </summary>
/// <value>A <see cref="System.String"/> value.</value>
public string Name
{
get
{
return network.GetName();
}
set
{
network.SetName(value);
}
}
/// <summary>
/// Gets a unique identifier for the network.
/// </summary>
/// <value>A <see cref="System.Guid"/> value.</value>
public Guid NetworkId
{
get
{
return network.GetNetworkId();
}
}
}
}

Просмотреть файл

@ -0,0 +1,60 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
/// <summary>
/// An enumerable collection of <see cref="Network"/> objects.
/// </summary>
public class NetworkCollection : IEnumerable<Network>
{
#region Private Fields
IEnumerable networkEnumerable;
#endregion // Private Fields
internal NetworkCollection(IEnumerable networkEnumerable)
{
this.networkEnumerable = networkEnumerable;
}
#region IEnumerable<Network> Members
/// <summary>
/// Returns the strongly typed enumerator for this collection.
/// </summary>
/// <returns>An <see cref="System.Collections.Generic.IEnumerator{T}"/> object.</returns>
public IEnumerator<Network> GetEnumerator()
{
foreach (INetwork network in networkEnumerable)
{
yield return new Network(network);
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns the enumerator for this collection.
/// </summary>
///<returns>An <see cref="System.Collections.IEnumerator"/> object.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
foreach (INetwork network in networkEnumerable)
{
yield return new Network(network);
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,115 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
/// <summary>
/// Represents a connection to a network.
/// </summary>
/// <remarks> A collection containing instances of this class is obtained by calling
/// the <see cref="P:Microsoft.WindowsAPICodePack.Net.Network.Connections"/> property.</remarks>
public class NetworkConnection
{
#region Private Fields
INetworkConnection networkConnection;
#endregion // Private Fields
internal NetworkConnection(INetworkConnection networkConnection)
{
this.networkConnection = networkConnection;
}
/// <summary>
/// Retrieves an object that represents the network
/// associated with this connection.
/// </summary>
/// <returns>A <see cref="Network"/> object.</returns>
public Network Network
{
get
{
return new Network(networkConnection.GetNetwork());
}
}
/// <summary>
/// Gets the adapter identifier for this connection.
/// </summary>
/// <value>A <see cref="System.Guid"/> object.</value>
public Guid AdapterId
{
get
{
return networkConnection.GetAdapterId();
}
}
/// <summary>
/// Gets the unique identifier for this connection.
/// </summary>
/// <value>A <see cref="System.Guid"/> object.</value>
public Guid ConnectionId
{
get
{
return networkConnection.GetConnectionId();
}
}
/// <summary>
/// Gets a value that indicates the connectivity of this connection.
/// </summary>
/// <value>A <see cref="Connectivity"/> value.</value>
public ConnectivityStates Connectivity
{
get
{
return networkConnection.GetConnectivity();
}
}
/// <summary>
/// Gets a value that indicates whether the network associated
/// with this connection is
/// an Active Directory network and whether the machine
/// has been authenticated by Active Directory.
/// </summary>
/// <value>A <see cref="DomainType"/> value.</value>
public DomainType DomainType
{
get
{
return networkConnection.GetDomainType();
}
}
/// <summary>
/// Gets a value that indicates whether this
/// connection has Internet access.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
public bool IsConnectedToInternet
{
get
{
return networkConnection.IsConnectedToInternet;
}
}
/// <summary>
/// Gets a value that indicates whether this connection has
/// network connectivity.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
public bool IsConnected
{
get
{
return networkConnection.IsConnected;
}
}
}
}

Просмотреть файл

@ -0,0 +1,60 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Net
{
/// <summary>
/// An enumerable collection of <see cref="NetworkConnection"/> objects.
/// </summary>
public class NetworkConnectionCollection : IEnumerable<NetworkConnection>
{
#region Private Fields
IEnumerable networkConnectionEnumerable;
#endregion // Private Fields
internal NetworkConnectionCollection(IEnumerable networkConnectionEnumerable)
{
this.networkConnectionEnumerable = networkConnectionEnumerable;
}
#region IEnumerable<NetworkConnection> Members
/// <summary>
/// Returns the strongly typed enumerator for this collection.
/// </summary>
/// <returns>A <see cref="System.Collections.Generic.IEnumerator{T}"/> object.</returns>
public IEnumerator<NetworkConnection> GetEnumerator()
{
foreach (INetworkConnection networkConnection in networkConnectionEnumerable)
{
yield return new NetworkConnection(networkConnection);
}
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns the enumerator for this collection.
/// </summary>
///<returns>A <see cref="System.Collections.IEnumerator"/> object.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
foreach (INetworkConnection networkConnection in networkConnectionEnumerable)
{
yield return new NetworkConnection(networkConnection);
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,124 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Net
{
/// <summary>
/// Specifies types of network connectivity.
/// </summary>
[Flags]
public enum ConnectivityStates
{
/// <summary>
/// The underlying network interfaces have no
/// connectivity to any network.
/// </summary>
None = 0,
/// <summary>
/// There is connectivity to the Internet
/// using the IPv4 protocol.
/// </summary>
IPv4Internet = 0x40,
/// <summary>
/// There is connectivity to a routed network
/// using the IPv4 protocol.
/// </summary>
IPv4LocalNetwork = 0x20,
/// <summary>
/// There is connectivity to a network, but
/// the service cannot detect any IPv4
/// network traffic.
/// </summary>
IPv4NoTraffic = 1,
/// <summary>
/// There is connectivity to the local
/// subnet using the IPv4 protocol.
/// </summary>
IPv4Subnet = 0x10,
/// <summary>
/// There is connectivity to the Internet
/// using the IPv4 protocol.
/// </summary>
IPv6Internet = 0x400,
/// <summary>
/// There is connectivity to a local
/// network using the IPv6 protocol.
/// </summary>
IPv6LocalNetwork = 0x200,
/// <summary>
/// There is connectivity to a network,
/// but the service cannot detect any
/// IPv6 network traffic
/// </summary>
IPv6NoTraffic = 2,
/// <summary>
/// There is connectivity to the local
/// subnet using the IPv6 protocol.
/// </summary>
IPv6Subnet = 0x100
}
/// <summary>
/// Specifies the domain type of a network.
/// </summary>
public enum DomainType
{
/// <summary>
/// The network is not an Active Directory network.
/// </summary>
NonDomainNetwork = 0,
/// <summary>
/// The network is an Active Directory network, but this machine is not authenticated against it.
/// </summary>
DomainNetwork = 1,
/// <summary>
/// The network is an Active Directory network, and this machine is authenticated against it.
/// </summary>
DomainAuthenticated = 2,
}
/// <summary>
/// Specifies the trust level for a
/// network.
/// </summary>
public enum NetworkCategory
{
/// <summary>
/// The network is a public (untrusted) network.
/// </summary>
Public,
/// <summary>
/// The network is a private (trusted) network.
/// </summary>
Private,
/// <summary>
/// The network is authenticated against an Active Directory domain.
/// </summary>
Authenticated
}
/// <summary>
/// Specifies the level of connectivity for
/// networks returned by the
/// <see cref="NetworkListManager"/>
/// class.
/// </summary>
[Flags]
public enum NetworkConnectivityLevels
{
/// <summary>
/// Networks that the machine is connected to.
/// </summary>
Connected = 1,
/// <summary>
/// Networks that the machine is not connected to.
/// </summary>
Disconnected = 2,
/// <summary>
/// All networks.
/// </summary>
All = 3,
}
}

Просмотреть файл

@ -0,0 +1,132 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Net
{
/// <summary>
/// Provides access to objects that represent networks and network connections.
/// </summary>
public static class NetworkListManager
{
#region Private Fields
static NetworkListManagerClass manager = new NetworkListManagerClass();
#endregion // Private Fields
/// <summary>
/// Retrieves a collection of <see cref="Network"/> objects that represent the networks defined for this machine.
/// </summary>
/// <param name="level">
/// The <see cref="NetworkConnectivityLevels"/> that specify the connectivity level of the returned <see cref="Network"/> objects.
/// </param>
/// <returns>
/// A <see cref="NetworkCollection"/> of <see cref="Network"/> objects.
/// </returns>
public static NetworkCollection GetNetworks(NetworkConnectivityLevels level)
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return new NetworkCollection(manager.GetNetworks(level));
}
/// <summary>
/// Retrieves the <see cref="Network"/> identified by the specified network identifier.
/// </summary>
/// <param name="networkId">
/// A <see cref="System.Guid"/> that specifies the unique identifier for the network.
/// </param>
/// <returns>
/// The <see cref="Network"/> that represents the network identified by the identifier.
/// </returns>
public static Network GetNetwork(Guid networkId)
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return new Network(manager.GetNetwork(networkId));
}
/// <summary>
/// Retrieves a collection of <see cref="NetworkConnection"/> objects that represent the connections for this machine.
/// </summary>
/// <returns>
/// A <see cref="NetworkConnectionCollection"/> containing the network connections.
/// </returns>
public static NetworkConnectionCollection GetNetworkConnections()
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return new NetworkConnectionCollection(manager.GetNetworkConnections());
}
/// <summary>
/// Retrieves the <see cref="NetworkConnection"/> identified by the specified connection identifier.
/// </summary>
/// <param name="networkConnectionId">
/// A <see cref="System.Guid"/> that specifies the unique identifier for the network connection.
/// </param>
/// <returns>
/// The <see cref="NetworkConnection"/> identified by the specified identifier.
/// </returns>
public static NetworkConnection GetNetworkConnection(Guid networkConnectionId)
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return new NetworkConnection(manager.GetNetworkConnection(networkConnectionId));
}
/// <summary>
/// Gets a value that indicates whether this machine
/// has Internet connectivity.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool IsConnectedToInternet
{
get
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return manager.IsConnectedToInternet;
}
}
/// <summary>
/// Gets a value that indicates whether this machine
/// has network connectivity.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool IsConnected
{
get
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return manager.IsConnected;
}
}
/// <summary>
/// Gets the connectivity state of this machine.
/// </summary>
/// <value>A <see cref="Connectivity"/> value.</value>
public static ConnectivityStates Connectivity
{
get
{
// Throw PlatformNotSupportedException if the user is not running Vista or beyond
CoreHelpers.ThrowIfNotVista();
return manager.GetConnectivity();
}
}
}
}

Просмотреть файл

@ -0,0 +1,113 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// A snapshot of the state of the battery.
/// </summary>
public class BatteryState
{
internal BatteryState()
{
var state = Power.GetSystemBatteryState();
if (!state.BatteryPresent)
{
throw new InvalidOperationException(LocalizedMessages.PowerManagerBatteryNotPresent);
}
ACOnline = state.AcOnLine;
MaxCharge = (int)state.MaxCapacity;
CurrentCharge = (int)state.RemainingCapacity;
ChargeRate = (int)state.Rate;
uint estimatedTime = state.EstimatedTime;
if (estimatedTime != uint.MaxValue) // uint.MaxValue signifies indefinite estimated time (plugged in)
{
EstimatedTimeRemaining = new TimeSpan(0, 0, (int)estimatedTime);
}
else
{
EstimatedTimeRemaining = TimeSpan.MaxValue;
}
SuggestedCriticalBatteryCharge = (int)state.DefaultAlert1;
SuggestedBatteryWarningCharge = (int)state.DefaultAlert2;
}
#region Public properties
/// <summary>
/// Gets a value that indicates whether the battery charger is
/// operating on external power.
/// </summary>
/// <value>A <see cref="System.Boolean"/> value. <b>True</b> indicates the battery charger is operating on AC power.</value>
public bool ACOnline { get; private set; }
/// <summary>
/// Gets the maximum charge of the battery (in mW).
/// </summary>
/// <value>An <see cref="System.Int32"/> value.</value>
public int MaxCharge { get; private set; }
/// <summary>
/// Gets the current charge of the battery (in mW).
/// </summary>
/// <value>An <see cref="System.Int32"/> value.</value>
public int CurrentCharge { get; private set; }
/// <summary>
/// Gets the rate of discharge for the battery (in mW).
/// </summary>
/// <remarks>
/// If plugged in, fully charged: DischargeRate = 0.
/// If plugged in, charging: DischargeRate = positive mW per hour.
/// If unplugged: DischargeRate = negative mW per hour.
/// </remarks>
/// <value>An <see cref="System.Int32"/> value.</value>
public int ChargeRate { get; private set; }
/// <summary>
/// Gets the estimated time remaining until the battery is empty.
/// </summary>
/// <value>A <see cref="System.TimeSpan"/> object.</value>
public TimeSpan EstimatedTimeRemaining { get; private set; }
/// <summary>
/// Gets the manufacturer's suggested battery charge level
/// that should cause a critical alert to be sent to the user.
/// </summary>
/// <value>An <see cref="System.Int32"/> value.</value>
public int SuggestedCriticalBatteryCharge { get; private set; }
/// <summary>
/// Gets the manufacturer's suggested battery charge level
/// that should cause a warning to be sent to the user.
/// </summary>
/// <value>An <see cref="System.Int32"/> value.</value>
public int SuggestedBatteryWarningCharge { get; private set; }
#endregion
/// <summary>
/// Generates a string that represents this <b>BatteryState</b> object.
/// </summary>
/// <returns>A <see cref="System.String"/> representation of this object's current state.</returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.BatteryStateStringRepresentation,
Environment.NewLine,
ACOnline,
MaxCharge,
CurrentCharge,
ChargeRate,
EstimatedTimeRemaining,
SuggestedCriticalBatteryCharge,
SuggestedBatteryWarningCharge
);
}
}
}

Просмотреть файл

@ -0,0 +1,91 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Threading;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// This class keeps track of the current state of each type of event.
/// The MessageManager class tracks event handlers.
/// This class only deals with each event type (i.e.
/// BatteryLifePercentChanged) as a whole.
/// </summary>
internal static class EventManager
{
// Prevents reading from PowerManager members while they are still null.
// MessageManager notifies the PowerManager that the member
// has been set and can be used.
internal static AutoResetEvent monitorOnReset = new AutoResetEvent(false);
#region Hardcoded GUIDS for each event
internal static readonly Guid PowerPersonalityChange = new Guid(0x245d8541, 0x3943, 0x4422, 0xb0, 0x25, 0x13, 0xA7, 0x84, 0xF6, 0x79, 0xB7);
internal static readonly Guid PowerSourceChange = new Guid(0x5d3e9a59, 0xe9D5, 0x4b00, 0xa6, 0xbd, 0xff, 0x34, 0xff, 0x51, 0x65, 0x48);
internal static readonly Guid BatteryCapacityChange = new Guid(0xa7ad8041, 0xb45a, 0x4cae, 0x87, 0xa3, 0xee, 0xcb, 0xb4, 0x68, 0xa9, 0xe1);
internal static readonly Guid BackgroundTaskNotification = new Guid(0x515c31d8, 0xf734, 0x163d, 0xa0, 0xfd, 0x11, 0xa0, 0x8c, 0x91, 0xe8, 0xf1);
internal static readonly Guid MonitorPowerStatus = new Guid(0x02731015, 0x4510, 0x4526, 0x99, 0xe6, 0xe5, 0xa1, 0x7e, 0xbd, 0x1a, 0xea);
#endregion
#region private static members
// Used to catch the initial message Windows sends when
// you first register for a power notification.
// We do not want to fire any event handlers when this happens.
private static bool personalityCaught;
private static bool powerSrcCaught;
private static bool batteryLifeCaught;
private static bool monitorOnCaught;
#endregion
/// <summary>
/// Determines if a message should be caught, preventing
/// the event handler from executing.
/// This is needed when an event is initially registered.
/// </summary>
/// <param name="eventGuid">The event to check.</param>
/// <returns>A boolean value. Returns true if the
/// message should be caught.</returns>
internal static bool IsMessageCaught(Guid eventGuid)
{
bool isMessageCaught = false;
if (eventGuid == EventManager.BatteryCapacityChange)
{
if (!batteryLifeCaught)
{
batteryLifeCaught = true;
isMessageCaught = true;
}
}
else if (eventGuid == EventManager.MonitorPowerStatus)
{
if (!monitorOnCaught)
{
monitorOnCaught = true;
isMessageCaught = true;
}
}
else if (eventGuid == EventManager.PowerPersonalityChange)
{
if (!personalityCaught)
{
personalityCaught = true;
isMessageCaught = true;
}
}
else if (eventGuid == EventManager.PowerSourceChange)
{
if (!powerSrcCaught)
{
powerSrcCaught = true;
isMessageCaught = true;
}
}
return isMessageCaught;
}
}
}

Просмотреть файл

@ -0,0 +1,41 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Enumeration of execution states.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2217:DoNotMarkEnumsWithFlags")]
[Flags]
public enum ExecutionStates
{
/// <summary>
/// No state configured.
/// </summary>
None = 0,
/// <summary>
/// Forces the system to be in the working state by resetting the system idle timer.
/// </summary>
SystemRequired = 0x1,
/// <summary>
/// Forces the display to be on by resetting the display idle timer.
/// </summary>
DisplayRequired = 0x2,
/// <summary>
/// Enables away mode. This value must be specified with ES_CONTINUOUS.
/// Away mode should be used only by media-recording and media-distribution applications that must perform critical background processing on desktop computers while the computer appears to be sleeping. See Remarks.
///
/// Windows Server 2003 and Windows XP/2000: ES_AWAYMODE_REQUIRED is not supported.
/// </summary>
AwayModeRequired = 0x40,
/// <summary>
/// Informs the system that the state being set should remain in effect until the next call that uses ES_CONTINUOUS and one of the other state flags is cleared.
/// </summary>
Continuous = unchecked((int)0x80000000)
}
}

Просмотреть файл

@ -0,0 +1,180 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// This class generates .NET events based on Windows messages.
/// The PowerRegWindow class processes the messages from Windows.
/// </summary>
internal static class MessageManager
{
private static object lockObject = new object();
private static PowerRegWindow window;
#region Internal static methods
/// <summary>
/// Registers a callback for a power event.
/// </summary>
/// <param name="eventId">Guid for the event.</param>
/// <param name="eventToRegister">Event handler for the specified event.</param>
internal static void RegisterPowerEvent(Guid eventId, EventHandler eventToRegister)
{
EnsureInitialized();
window.RegisterPowerEvent(eventId, eventToRegister);
}
/// <summary>
/// Unregisters an event handler for a power event.
/// </summary>
/// <param name="eventId">Guid for the event.</param>
/// <param name="eventToUnregister">Event handler to unregister.</param>
internal static void UnregisterPowerEvent(Guid eventId, EventHandler eventToUnregister)
{
EnsureInitialized();
window.UnregisterPowerEvent(eventId, eventToUnregister);
}
#endregion
/// <summary>
/// Ensures that the hidden window is initialized and
/// listening for messages.
/// </summary>
private static void EnsureInitialized()
{
lock (lockObject)
{
if (window == null)
{
// Create a new hidden window to listen
// for power management related window messages.
window = new PowerRegWindow();
}
}
}
/// <summary>
/// Catch Windows messages and generates events for power specific
/// messages.
/// </summary>
internal class PowerRegWindow : Form
{
private Hashtable eventList = new Hashtable();
private ReaderWriterLock readerWriterLock = new ReaderWriterLock();
internal PowerRegWindow()
: base()
{
}
#region Internal Methods
/// <summary>
/// Adds an event handler to call when Windows sends
/// a message for an event.
/// </summary>
/// <param name="eventId">Guid for the event.</param>
/// <param name="eventToRegister">Event handler for the event.</param>
internal void RegisterPowerEvent(Guid eventId, EventHandler eventToRegister)
{
readerWriterLock.AcquireWriterLock(Timeout.Infinite);
if (!eventList.Contains(eventId))
{
Power.RegisterPowerSettingNotification(this.Handle, eventId);
ArrayList newList = new ArrayList();
newList.Add(eventToRegister);
eventList.Add(eventId, newList);
}
else
{
ArrayList currList = (ArrayList)eventList[eventId];
currList.Add(eventToRegister);
}
readerWriterLock.ReleaseWriterLock();
}
/// <summary>
/// Removes an event handler.
/// </summary>
/// <param name="eventId">Guid for the event.</param>
/// <param name="eventToUnregister">Event handler to remove.</param>
/// <exception cref="InvalidOperationException">Cannot unregister
/// a function that is not registered.</exception>
internal void UnregisterPowerEvent(Guid eventId, EventHandler eventToUnregister)
{
readerWriterLock.AcquireWriterLock(Timeout.Infinite);
if (eventList.Contains(eventId))
{
ArrayList currList = (ArrayList)eventList[eventId];
currList.Remove(eventToUnregister);
}
else
{
throw new InvalidOperationException(LocalizedMessages.MessageManagerHandlerNotRegistered);
}
readerWriterLock.ReleaseWriterLock();
}
#endregion
/// <summary>
/// Executes any registered event handlers.
/// </summary>
/// <param name="eventHandlerList">ArrayList of event handlers.</param>
private static void ExecuteEvents(ArrayList eventHandlerList)
{
foreach (EventHandler handler in eventHandlerList)
{
handler.Invoke(null, new EventArgs());
}
}
/// <summary>
/// This method is called when a Windows message
/// is sent to this window.
/// The method calls the registered event handlers.
/// </summary>
protected override void WndProc(ref Message m)
{
// Make sure it is a Power Management message.
if (m.Msg == PowerManagementNativeMethods.PowerBroadcastMessage &&
(int)m.WParam == PowerManagementNativeMethods.PowerSettingChangeMessage)
{
PowerManagementNativeMethods.PowerBroadcastSetting ps =
(PowerManagementNativeMethods.PowerBroadcastSetting)Marshal.PtrToStructure(
m.LParam, typeof(PowerManagementNativeMethods.PowerBroadcastSetting));
IntPtr pData = new IntPtr(m.LParam.ToInt64() + Marshal.SizeOf(ps));
Guid currentEvent = ps.PowerSetting;
// IsMonitorOn
if (ps.PowerSetting == EventManager.MonitorPowerStatus &&
ps.DataLength == Marshal.SizeOf(typeof(Int32)))
{
Int32 monitorStatus = (Int32)Marshal.PtrToStructure(pData, typeof(Int32));
PowerManager.IsMonitorOn = monitorStatus != 0;
EventManager.monitorOnReset.Set();
}
if (!EventManager.IsMessageCaught(currentEvent))
{
ExecuteEvents((ArrayList)eventList[currentEvent]);
}
}
else
base.WndProc(ref m);
}
}
}
}

Просмотреть файл

@ -0,0 +1,27 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
internal static class PowerPersonalityGuids
{
internal static readonly Guid HighPerformance = new Guid(0x8c5e7fda, 0xe8bf, 0x4a96, 0x9a, 0x85, 0xa6, 0xe2, 0x3a, 0x8c, 0x63, 0x5c);
internal static readonly Guid PowerSaver = new Guid(0xa1841308, 0x3541, 0x4fab, 0xbc, 0x81, 0xf7, 0x15, 0x56, 0xf2, 0x0b, 0x4a);
internal static readonly Guid Automatic = new Guid(0x381b4222, 0xf694, 0x41f0, 0x96, 0x85, 0xff, 0x5b, 0xb2, 0x60, 0xdf, 0x2e);
internal static readonly Guid All = new Guid(0x68A1E95E, 0x13EA, 0x41E1, 0x80, 0x11, 0x0C, 0x49, 0x6C, 0xA4, 0x90, 0xB0);
internal static PowerPersonality GuidToEnum(Guid guid)
{
if (guid == HighPerformance)
return PowerPersonality.HighPerformance;
else if (guid == PowerSaver)
return PowerPersonality.PowerSaver;
else if (guid == Automatic)
return PowerPersonality.Automatic;
else
return PowerPersonality.Unknown;
}
}
}

Просмотреть файл

@ -0,0 +1,72 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
internal static class Power
{
internal static PowerManagementNativeMethods.SystemPowerCapabilities
GetSystemPowerCapabilities()
{
PowerManagementNativeMethods.SystemPowerCapabilities powerCap;
uint retval = PowerManagementNativeMethods.CallNtPowerInformation(
PowerManagementNativeMethods.PowerInformationLevel.SystemPowerCapabilities,
IntPtr.Zero, 0, out powerCap,
(UInt32)Marshal.SizeOf(typeof(PowerManagementNativeMethods.SystemPowerCapabilities))
);
if (retval == CoreNativeMethods.StatusAccessDenied)
{
throw new UnauthorizedAccessException(LocalizedMessages.PowerInsufficientAccessCapabilities);
}
return powerCap;
}
internal static PowerManagementNativeMethods.SystemBatteryState GetSystemBatteryState()
{
PowerManagementNativeMethods.SystemBatteryState batteryState;
uint retval = PowerManagementNativeMethods.CallNtPowerInformation(
PowerManagementNativeMethods.PowerInformationLevel.SystemBatteryState,
IntPtr.Zero, 0, out batteryState,
(UInt32)Marshal.SizeOf(typeof(PowerManagementNativeMethods.SystemBatteryState))
);
if (retval == CoreNativeMethods.StatusAccessDenied)
{
throw new UnauthorizedAccessException(LocalizedMessages.PowerInsufficientAccessBatteryState);
}
return batteryState;
}
/// <summary>
/// Registers the application to receive power setting notifications
/// for the specific power setting event.
/// </summary>
/// <param name="handle">Handle indicating where the power setting
/// notifications are to be sent.</param>
/// <param name="powerSetting">The GUID of the power setting for
/// which notifications are to be sent.</param>
/// <returns>Returns a notification handle for unregistering
/// power notifications.</returns>
internal static int RegisterPowerSettingNotification(
IntPtr handle, Guid powerSetting)
{
int outHandle = PowerManagementNativeMethods.RegisterPowerSettingNotification(
handle,
ref powerSetting,
0);
return outHandle;
}
}
}

Просмотреть файл

@ -0,0 +1,404 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Diagnostics.CodeAnalysis;
using Microsoft.WindowsAPICodePack.Resources;
using MS.WindowsAPICodePack.Internal;
using System.ComponentModel;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Enables registration for
/// power-related event notifications and provides access to power settings.
/// </summary>
public static class PowerManager
{
private static bool? isMonitorOn;
private static bool monitorRequired;
private static bool requestBlockSleep;
private static readonly object monitoronlock = new object();
#region Notifications
/// <summary>
/// Raised each time the active power scheme changes.
/// </summary>
/// <exception cref="InvalidOperationException">The event handler specified for removal was not registered.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
public static event EventHandler PowerPersonalityChanged
{
add
{
MessageManager.RegisterPowerEvent(
EventManager.PowerPersonalityChange, value);
}
remove
{
CoreHelpers.ThrowIfNotVista();
MessageManager.UnregisterPowerEvent(
EventManager.PowerPersonalityChange, value);
}
}
/// <summary>
/// Raised when the power source changes.
/// </summary>
/// <exception cref="InvalidOperationException">The event handler specified for removal was not registered.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
public static event EventHandler PowerSourceChanged
{
add
{
CoreHelpers.ThrowIfNotVista();
MessageManager.RegisterPowerEvent(
EventManager.PowerSourceChange, value);
}
remove
{
CoreHelpers.ThrowIfNotVista();
MessageManager.UnregisterPowerEvent(
EventManager.PowerSourceChange, value);
}
}
/// <summary>
/// Raised when the remaining battery life changes.
/// </summary>
/// <exception cref="InvalidOperationException">The event handler specified for removal was not registered.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
public static event EventHandler BatteryLifePercentChanged
{
add
{
CoreHelpers.ThrowIfNotVista();
MessageManager.RegisterPowerEvent(
EventManager.BatteryCapacityChange, value);
}
remove
{
CoreHelpers.ThrowIfNotVista();
MessageManager.UnregisterPowerEvent(
EventManager.BatteryCapacityChange, value);
}
}
/// <summary>
/// Raised when the monitor status changes.
/// </summary>
/// <exception cref="InvalidOperationException">The event handler specified for removal was not registered.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
public static event EventHandler IsMonitorOnChanged
{
add
{
CoreHelpers.ThrowIfNotVista();
MessageManager.RegisterPowerEvent(
EventManager.MonitorPowerStatus, value);
}
remove
{
CoreHelpers.ThrowIfNotVista();
MessageManager.UnregisterPowerEvent(
EventManager.MonitorPowerStatus, value);
}
}
/// <summary>
/// Raised when the system will not be moving into an idle
/// state in the near future so applications should
/// perform any tasks that
/// would otherwise prevent the computer from entering an idle state.
/// </summary>
/// <exception cref="InvalidOperationException">The event handler specified for removal was not registered.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
public static event EventHandler SystemBusyChanged
{
add
{
CoreHelpers.ThrowIfNotVista();
MessageManager.RegisterPowerEvent(
EventManager.BackgroundTaskNotification, value);
}
remove
{
CoreHelpers.ThrowIfNotVista();
MessageManager.UnregisterPowerEvent(
EventManager.BackgroundTaskNotification, value);
}
}
#endregion
/// <summary>
/// Gets a snapshot of the current battery state.
/// </summary>
/// <returns>A <see cref="BatteryState"/> instance that represents
/// the state of the battery at the time this method was called.</returns>
/// <exception cref="System.InvalidOperationException">The system does not have a battery.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires XP/Windows Server 2003 or higher.</exception>
public static BatteryState GetCurrentBatteryState()
{
CoreHelpers.ThrowIfNotXP();
return new BatteryState();
}
#region Power System Properties
/// <summary>
/// Gets or sets a value that indicates whether the monitor is
/// set to remain active.
/// </summary>
/// <exception cref="T:System.PlatformNotSupportedException">Requires XP/Windows Server 2003 or higher.</exception>
/// <exception cref="T:System.Security.SecurityException">The caller does not have sufficient privileges to set this property.
/// </exception>
/// <remarks>This information is typically used by applications
/// that display information but do not require
/// user interaction. For example, video playback applications.</remarks>
/// <permission cref="T:System.Security.Permissions.SecurityPermission"> to set this property. Demand value: <see cref="F:System.Security.Permissions.SecurityAction.Demand"/>; Named Permission Sets: <b>FullTrust</b>.</permission>
/// <value>A <see cref="System.Boolean"/> value. <b>True</b> if the monitor
/// is required to remain on.</value>
public static bool MonitorRequired
{
get
{
CoreHelpers.ThrowIfNotXP();
return monitorRequired;
}
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
set
{
CoreHelpers.ThrowIfNotXP();
if (value)
{
PowerManager.SetThreadExecutionState(ExecutionStates.Continuous | ExecutionStates.DisplayRequired);
}
else
{
PowerManager.SetThreadExecutionState(ExecutionStates.Continuous);
}
monitorRequired = value;
}
}
/// <summary>
/// Gets or sets a value that indicates whether the system
/// is required to be in the working state.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires XP/Windows Server 2003 or higher.</exception>
/// <exception cref="System.Security.SecurityException">The caller does not have sufficient privileges to set this property.
/// </exception>
/// <permission cref="System.Security.Permissions.SecurityPermission"> to set this property. Demand value: <see cref="F:System.Security.Permissions.SecurityAction.Demand"/>; Named Permission Sets: <b>FullTrust</b>.</permission>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool RequestBlockSleep
{
get
{
CoreHelpers.ThrowIfNotXP();
return requestBlockSleep;
}
[System.Security.Permissions.PermissionSetAttribute(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
set
{
CoreHelpers.ThrowIfNotXP();
if (value)
PowerManager.SetThreadExecutionState(ExecutionStates.Continuous | ExecutionStates.SystemRequired);
else
PowerManager.SetThreadExecutionState(ExecutionStates.Continuous);
requestBlockSleep = value;
}
}
/// <summary>
/// Gets a value that indicates whether a battery is present.
/// The battery can be a short term battery.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires XP/Windows Server 2003 or higher.</exception>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool IsBatteryPresent
{
get
{
CoreHelpers.ThrowIfNotXP();
return Power.GetSystemBatteryState().BatteryPresent;
}
}
/// <summary>
/// Gets a value that indicates whether the battery is a short term battery.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires XP/Windows Server 2003 or higher.</exception>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool IsBatteryShortTerm
{
get
{
CoreHelpers.ThrowIfNotXP();
return Power.GetSystemPowerCapabilities().BatteriesAreShortTerm;
}
}
/// <summary>
/// Gets a value that indicates a UPS is present to prevent
/// sudden loss of power.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires XP/Windows Server 2003 or higher.</exception>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool IsUpsPresent
{
get
{
CoreHelpers.ThrowIfNotXP();
// Because the native method doesn't return the correct value for .UpsPresent,
// use .BatteriesAreShortTerm and .SystemBatteriesPresent to check for UPS
PowerManagementNativeMethods.SystemPowerCapabilities batt = Power.GetSystemPowerCapabilities();
return (batt.BatteriesAreShortTerm && batt.SystemBatteriesPresent);
}
}
/// <summary>
/// Gets a value that indicates the current power scheme.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
/// <value>A <see cref="PowerPersonality"/> value.</value>
public static PowerPersonality PowerPersonality
{
get
{
Guid guid;
PowerManagementNativeMethods.PowerGetActiveScheme(IntPtr.Zero, out guid);
try
{
return PowerPersonalityGuids.GuidToEnum(guid);
}
finally
{
CoreNativeMethods.LocalFree(ref guid);
}
}
}
/// <summary>
/// Gets a value that indicates the remaining battery life
/// (as a percentage of the full battery charge).
/// This value is in the range 0-100,
/// where 0 is not charged and 100 is fully charged.
/// </summary>
/// <exception cref="System.InvalidOperationException">The system does not have a battery.</exception>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
/// <value>An <see cref="System.Int32"/> value.</value>
public static int BatteryLifePercent
{
get
{
// Because of the way this value is being calculated, it should not be limited to granularity
// as the data from the event (old way) was.
CoreHelpers.ThrowIfNotVista();
if (!Power.GetSystemBatteryState().BatteryPresent)
throw new InvalidOperationException(LocalizedMessages.PowerManagerBatteryNotPresent);
var state = Power.GetSystemBatteryState();
int percent = (int)Math.Round(((double)state.RemainingCapacity / state.MaxCapacity * 100), 0);
return percent;
}
}
/// <summary>
/// Gets a value that indictates whether the monitor is on.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
/// <value>A <see cref="System.Boolean"/> value.</value>
public static bool IsMonitorOn
{
get
{
CoreHelpers.ThrowIfNotVista();
lock (monitoronlock)
{
if (isMonitorOn == null)
{
EventHandler dummy = delegate(object sender, EventArgs args) { };
IsMonitorOnChanged += dummy;
// Wait until Windows updates the power source
// (through RegisterPowerSettingNotification)
EventManager.monitorOnReset.WaitOne();
}
}
return (bool)isMonitorOn;
}
internal set { isMonitorOn = value; }
}
/// <summary>
/// Gets the current power source.
/// </summary>
/// <exception cref="System.PlatformNotSupportedException">Requires Vista/Windows Server 2008.</exception>
/// <value>A <see cref="PowerSource"/> value.</value>
public static PowerSource PowerSource
{
get
{
CoreHelpers.ThrowIfNotVista();
if (IsUpsPresent)
{
return PowerSource.Ups;
}
if (!IsBatteryPresent || GetCurrentBatteryState().ACOnline)
{
return PowerSource.AC;
}
return PowerSource.Battery;
}
}
#endregion
/// <summary>
/// Allows an application to inform the system that it
/// is in use, thereby preventing the system from entering
/// the sleeping power state or turning off the display
/// while the application is running.
/// </summary>
/// <param name="executionStateOptions">The thread's execution requirements.</param>
/// <exception cref="Win32Exception">Thrown if the SetThreadExecutionState call fails.</exception>
public static void SetThreadExecutionState(ExecutionStates executionStateOptions)
{
ExecutionStates ret = PowerManagementNativeMethods.SetThreadExecutionState(executionStateOptions);
if (ret == ExecutionStates.None)
{
throw new Win32Exception(LocalizedMessages.PowerExecutionStateFailed);
}
}
}
}

Просмотреть файл

@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// This exception is thrown when there are problems with getting piece of data within PowerManager.
/// </summary>
[Serializable]
public class PowerManagerException : Exception
{
/// <summary>
/// Default constructor.
/// </summary>
public PowerManagerException() { }
/// <summary>
/// Initializes an excpetion with a custom message.
/// </summary>
/// <param name="message">A custom message for the exception.</param>
public PowerManagerException(string message) : base(message) { }
/// <summary>
/// Initializes an exception with custom message and inner exception.
/// </summary>
/// <param name="message">A custom message for the exception.</param>
/// <param name="innerException">An inner exception on which to base this exception.</param>
public PowerManagerException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes an exception from serialization info and a context.
/// </summary>
/// <param name="info">SerializationInfo for the exception.</param>
/// <param name="context">StreamingContext for the exception.</param>
protected PowerManagerException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
}
}

Просмотреть файл

@ -0,0 +1,33 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Specifies the supported power personalities.
/// </summary>
public enum PowerPersonality
{
/// <summary>
/// The power personality Guid does not match a known value.
/// </summary>
Unknown,
/// <summary>
/// Power settings designed to deliver maximum performance
/// at the expense of power consumption savings.
/// </summary>
HighPerformance,
/// <summary>
/// Power settings designed consume minimum power
/// at the expense of system performance and responsiveness.
/// </summary>
PowerSaver,
/// <summary>
/// Power settings designed to balance performance
/// and power consumption.
/// </summary>
Automatic
}
}

Просмотреть файл

@ -0,0 +1,34 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.ApplicationServices
{
/// <summary>
/// Specifies the power source currently supplying power to the system.
/// </summary>
/// <remarks>Application should be aware of the power source because
/// some power sources provide a finite power supply.
/// An application might take steps to conserve power while
/// the system is using such a source.
/// </remarks>
public enum PowerSource
{
/// <summary>
/// The computer is powered by an AC power source
/// or a similar device, such as a laptop powered
/// by a 12V automotive adapter.
/// </summary>
AC = 0,
/// <summary>
/// The computer is powered by a built-in battery.
/// A battery has a limited
/// amount of power; applications should conserve resources
/// where possible.
/// </summary>
Battery = 1,
/// <summary>
/// The computer is powered by a short-term power source
/// such as a UPS device.
/// </summary>
Ups = 2
}
}

Просмотреть файл

@ -0,0 +1,43 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Microsoft.WindowsAPICodePack")]
[assembly: AssemblyDescription("WindowsAPICodePack Core")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("Microsoft Windows API Code Pack for .NET Framework")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: InternalsVisibleTo("Microsoft.WindowsAPICodePack.Shell")]
[assembly: InternalsVisibleTo("Microsoft.WindowsAPICodePack.Sensors")]
[assembly: InternalsVisibleTo("Microsoft.WindowsAPICodePack.ShellExtensions")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ac9740bc-3035-43ee-9a68-1dde36ab1f5e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: NeutralResourcesLanguageAttribute("en")]

Просмотреть файл

@ -0,0 +1,808 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Resources;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Represents the OLE struct PROPVARIANT.
/// This class is intended for internal use only.
/// </summary>
/// <remarks>
/// Originally sourced from http://blogs.msdn.com/adamroot/pages/interop-with-propvariants-in-net.aspx
/// and modified to support additional types including vectors and ability to set values
/// </remarks>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Portability", "CA1900:ValueTypeFieldsShouldBePortable", MessageId = "_ptr2")]
[StructLayout(LayoutKind.Explicit)]
public sealed class PropVariant : IDisposable
{
#region Vector Action Cache
// A static dictionary of delegates to get data from array's contained within PropVariants
private static Dictionary<Type, Action<PropVariant, Array, uint>> _vectorActions = null;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
private static Dictionary<Type, Action<PropVariant, Array, uint>> GenerateVectorActions()
{
Dictionary<Type, Action<PropVariant, Array, uint>> cache = new Dictionary<Type, Action<PropVariant, Array, uint>>();
cache.Add(typeof(Int16), (pv, array, i) =>
{
short val;
PropVariantNativeMethods.PropVariantGetInt16Elem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(UInt16), (pv, array, i) =>
{
ushort val;
PropVariantNativeMethods.PropVariantGetUInt16Elem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(Int32), (pv, array, i) =>
{
int val;
PropVariantNativeMethods.PropVariantGetInt32Elem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(UInt32), (pv, array, i) =>
{
uint val;
PropVariantNativeMethods.PropVariantGetUInt32Elem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(Int64), (pv, array, i) =>
{
long val;
PropVariantNativeMethods.PropVariantGetInt64Elem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(UInt64), (pv, array, i) =>
{
ulong val;
PropVariantNativeMethods.PropVariantGetUInt64Elem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(DateTime), (pv, array, i) =>
{
System.Runtime.InteropServices.ComTypes.FILETIME val;
PropVariantNativeMethods.PropVariantGetFileTimeElem(pv, i, out val);
long fileTime = GetFileTimeAsLong(ref val);
array.SetValue(DateTime.FromFileTime(fileTime), i);
});
cache.Add(typeof(Boolean), (pv, array, i) =>
{
bool val;
PropVariantNativeMethods.PropVariantGetBooleanElem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(Double), (pv, array, i) =>
{
double val;
PropVariantNativeMethods.PropVariantGetDoubleElem(pv, i, out val);
array.SetValue(val, i);
});
cache.Add(typeof(Single), (pv, array, i) => // float
{
float[] val = new float[1];
Marshal.Copy(pv._ptr2, val, (int)i, 1);
array.SetValue(val[0], (int)i);
});
cache.Add(typeof(Decimal), (pv, array, i) =>
{
int[] val = new int[4];
for (int a = 0; a < val.Length; a++)
{
val[a] = Marshal.ReadInt32(pv._ptr2,
(int)i * sizeof(decimal) + a * sizeof(int)); //index * size + offset quarter
}
array.SetValue(new decimal(val), i);
});
cache.Add(typeof(String), (pv, array, i) =>
{
string val = string.Empty;
PropVariantNativeMethods.PropVariantGetStringElem(pv, i, ref val);
array.SetValue(val, i);
});
return cache;
}
#endregion
#region Dynamic Construction / Factory (Expressions)
/// <summary>
/// Attempts to create a PropVariant by finding an appropriate constructor.
/// </summary>
/// <param name="value">Object from which PropVariant should be created.</param>
public static PropVariant FromObject(object value)
{
if (value == null)
{
return new PropVariant();
}
else
{
var func = GetDynamicConstructor(value.GetType());
return func(value);
}
}
// A dictionary and lock to contain compiled expression trees for constructors
private static Dictionary<Type, Func<object, PropVariant>> _cache = new Dictionary<Type, Func<object, PropVariant>>();
private static object _padlock = new object();
// Retrieves a cached constructor expression.
// If no constructor has been cached, it attempts to find/add it. If it cannot be found
// an exception is thrown.
// This method looks for a public constructor with the same parameter type as the object.
private static Func<object, PropVariant> GetDynamicConstructor(Type type)
{
lock (_padlock)
{
// initial check, if action is found, return it
Func<object, PropVariant> action;
if (!_cache.TryGetValue(type, out action))
{
// iterates through all constructors
ConstructorInfo constructor = typeof(PropVariant)
.GetConstructor(new Type[] { type });
if (constructor == null)
{ // if the method was not found, throw.
throw new ArgumentException(LocalizedMessages.PropVariantTypeNotSupported);
}
else // if the method was found, create an expression to call it.
{
// create parameters to action
var arg = Expression.Parameter(typeof(object), "arg");
// create an expression to invoke the constructor with an argument cast to the correct type
var create = Expression.New(constructor, Expression.Convert(arg, type));
// compiles expression into an action delegate
action = Expression.Lambda<Func<object, PropVariant>>(create, arg).Compile();
_cache.Add(type, action);
}
}
return action;
}
}
#endregion
#region Fields
[FieldOffset(0)]
decimal _decimal;
// This is actually a VarEnum value, but the VarEnum type
// requires 4 bytes instead of the expected 2.
[FieldOffset(0)]
ushort _valueType;
// Reserved Fields
//[FieldOffset(2)]
//ushort _wReserved1;
//[FieldOffset(4)]
//ushort _wReserved2;
//[FieldOffset(6)]
//ushort _wReserved3;
// In order to allow x64 compat, we need to allow for
// expansion of the IntPtr. However, the BLOB struct
// uses a 4-byte int, followed by an IntPtr, so
// although the valueData field catches most pointer values,
// we need an additional 4-bytes to get the BLOB
// pointer. The valueDataExt field provides this, as well as
// the last 4-bytes of an 8-byte value on 32-bit
// architectures.
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
[FieldOffset(12)]
IntPtr _ptr2;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")]
[FieldOffset(8)]
IntPtr _ptr;
[FieldOffset(8)]
Int32 _int32;
[FieldOffset(8)]
UInt32 _uint32;
[FieldOffset(8)]
byte _byte;
[FieldOffset(8)]
sbyte _sbyte;
[FieldOffset(8)]
short _short;
[FieldOffset(8)]
ushort _ushort;
[FieldOffset(8)]
long _long;
[FieldOffset(8)]
ulong _ulong;
[FieldOffset(8)]
double _double;
[FieldOffset(8)]
float _float;
#endregion // struct fields
#region Constructors
/// <summary>
/// Default constrcutor
/// </summary>
public PropVariant()
{
// left empty
}
/// <summary>
/// Set a string value
/// </summary>
public PropVariant(string value)
{
if (value == null)
{
throw new ArgumentException(LocalizedMessages.PropVariantNullString, "value");
}
_valueType = (ushort)VarEnum.VT_LPWSTR;
_ptr = Marshal.StringToCoTaskMemUni(value);
}
/// <summary>
/// Set a string vector
/// </summary>
public PropVariant(string[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromStringVector(value, (uint)value.Length, this);
}
/// <summary>
/// Set a bool vector
/// </summary>
public PropVariant(bool[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromBooleanVector(value, (uint)value.Length, this);
}
/// <summary>
/// Set a short vector
/// </summary>
public PropVariant(short[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromInt16Vector(value, (uint)value.Length, this);
}
/// <summary>
/// Set a short vector
/// </summary>
public PropVariant(ushort[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromUInt16Vector(value, (uint)value.Length, this);
}
/// <summary>
/// Set an int vector
/// </summary>
public PropVariant(int[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromInt32Vector(value, (uint)value.Length, this);
}
/// <summary>
/// Set an uint vector
/// </summary>
public PropVariant(uint[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromUInt32Vector(value, (uint)value.Length, this);
}
/// <summary>
/// Set a long vector
/// </summary>
public PropVariant(long[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromInt64Vector(value, (uint)value.Length, this);
}
/// <summary>
/// Set a ulong vector
/// </summary>
public PropVariant(ulong[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromUInt64Vector(value, (uint)value.Length, this);
}
/// <summary>>
/// Set a double vector
/// </summary>
public PropVariant(double[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
PropVariantNativeMethods.InitPropVariantFromDoubleVector(value, (uint)value.Length, this);
}
/// <summary>
/// Set a DateTime vector
/// </summary>
public PropVariant(DateTime[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
System.Runtime.InteropServices.ComTypes.FILETIME[] fileTimeArr =
new System.Runtime.InteropServices.ComTypes.FILETIME[value.Length];
for (int i = 0; i < value.Length; i++)
{
fileTimeArr[i] = DateTimeToFileTime(value[i]);
}
PropVariantNativeMethods.InitPropVariantFromFileTimeVector(fileTimeArr, (uint)fileTimeArr.Length, this);
}
/// <summary>
/// Set a bool value
/// </summary>
public PropVariant(bool value)
{
_valueType = (ushort)VarEnum.VT_BOOL;
_int32 = (value == true) ? -1 : 0;
}
/// <summary>
/// Set a DateTime value
/// </summary>
public PropVariant(DateTime value)
{
_valueType = (ushort)VarEnum.VT_FILETIME;
System.Runtime.InteropServices.ComTypes.FILETIME ft = DateTimeToFileTime(value);
PropVariantNativeMethods.InitPropVariantFromFileTime(ref ft, this);
}
/// <summary>
/// Set a byte value
/// </summary>
public PropVariant(byte value)
{
_valueType = (ushort)VarEnum.VT_UI1;
_byte = value;
}
/// <summary>
/// Set a sbyte value
/// </summary>
public PropVariant(sbyte value)
{
_valueType = (ushort)VarEnum.VT_I1;
_sbyte = value;
}
/// <summary>
/// Set a short value
/// </summary>
public PropVariant(short value)
{
_valueType = (ushort)VarEnum.VT_I2;
_short = value;
}
/// <summary>
/// Set an unsigned short value
/// </summary>
public PropVariant(ushort value)
{
_valueType = (ushort)VarEnum.VT_UI2;
_ushort = value;
}
/// <summary>
/// Set an int value
/// </summary>
public PropVariant(int value)
{
_valueType = (ushort)VarEnum.VT_I4;
_int32 = value;
}
/// <summary>
/// Set an unsigned int value
/// </summary>
public PropVariant(uint value)
{
_valueType = (ushort)VarEnum.VT_UI4;
_uint32 = value;
}
/// <summary>
/// Set a decimal value
/// </summary>
public PropVariant(decimal value)
{
_decimal = value;
// It is critical that the value type be set after the decimal value, because they overlap.
// If valuetype is written first, its value will be lost when _decimal is written.
_valueType = (ushort)VarEnum.VT_DECIMAL;
}
/// <summary>
/// Create a PropVariant with a contained decimal array.
/// </summary>
/// <param name="value">Decimal array to wrap.</param>
public PropVariant(decimal[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
_valueType = (ushort)(VarEnum.VT_DECIMAL | VarEnum.VT_VECTOR);
_int32 = value.Length;
// allocate required memory for array with 128bit elements
_ptr2 = Marshal.AllocCoTaskMem(value.Length * sizeof(decimal));
for (int i = 0; i < value.Length; i++)
{
int[] bits = decimal.GetBits(value[i]);
Marshal.Copy(bits, 0, _ptr2, bits.Length);
}
}
/// <summary>
/// Create a PropVariant containing a float type.
/// </summary>
public PropVariant(float value)
{
_valueType = (ushort)VarEnum.VT_R4;
_float = value;
}
/// <summary>
/// Creates a PropVariant containing a float[] array.
/// </summary>
public PropVariant(float[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
_valueType = (ushort)(VarEnum.VT_R4 | VarEnum.VT_VECTOR);
_int32 = value.Length;
_ptr2 = Marshal.AllocCoTaskMem(value.Length * sizeof(float));
Marshal.Copy(value, 0, _ptr2, value.Length);
}
/// <summary>
/// Set a long
/// </summary>
public PropVariant(long value)
{
_long = value;
_valueType = (ushort)VarEnum.VT_I8;
}
/// <summary>
/// Set a ulong
/// </summary>
public PropVariant(ulong value)
{
_valueType = (ushort)VarEnum.VT_UI8;
_ulong = value;
}
/// <summary>
/// Set a double
/// </summary>
public PropVariant(double value)
{
_valueType = (ushort)VarEnum.VT_R8;
_double = value;
}
#endregion
#region Uncalled methods - These are currently not called, but I think may be valid in the future.
/// <summary>
/// Set an IUnknown value
/// </summary>
/// <param name="value">The new value to set.</param>
internal void SetIUnknown(object value)
{
_valueType = (ushort)VarEnum.VT_UNKNOWN;
_ptr = Marshal.GetIUnknownForObject(value);
}
/// <summary>
/// Set a safe array value
/// </summary>
/// <param name="array">The new value to set.</param>
internal void SetSafeArray(Array array)
{
if (array == null) { throw new ArgumentNullException("array"); }
const ushort vtUnknown = 13;
IntPtr psa = PropVariantNativeMethods.SafeArrayCreateVector(vtUnknown, 0, (uint)array.Length);
IntPtr pvData = PropVariantNativeMethods.SafeArrayAccessData(psa);
try // to remember to release lock on data
{
for (int i = 0; i < array.Length; ++i)
{
object obj = array.GetValue(i);
IntPtr punk = (obj != null) ? Marshal.GetIUnknownForObject(obj) : IntPtr.Zero;
Marshal.WriteIntPtr(pvData, i * IntPtr.Size, punk);
}
}
finally
{
PropVariantNativeMethods.SafeArrayUnaccessData(psa);
}
_valueType = (ushort)VarEnum.VT_ARRAY | (ushort)VarEnum.VT_UNKNOWN;
_ptr = psa;
}
#endregion
#region public Properties
/// <summary>
/// Gets or sets the variant type.
/// </summary>
public VarEnum VarType
{
get { return (VarEnum)_valueType; }
set { _valueType = (ushort)value; }
}
/// <summary>
/// Checks if this has an empty or null value
/// </summary>
/// <returns></returns>
public bool IsNullOrEmpty
{
get
{
return (_valueType == (ushort)VarEnum.VT_EMPTY || _valueType == (ushort)VarEnum.VT_NULL);
}
}
/// <summary>
/// Gets the variant value.
/// </summary>
public object Value
{
get
{
switch ((VarEnum)_valueType)
{
case VarEnum.VT_I1:
return _sbyte;
case VarEnum.VT_UI1:
return _byte;
case VarEnum.VT_I2:
return _short;
case VarEnum.VT_UI2:
return _ushort;
case VarEnum.VT_I4:
case VarEnum.VT_INT:
return _int32;
case VarEnum.VT_UI4:
case VarEnum.VT_UINT:
return _uint32;
case VarEnum.VT_I8:
return _long;
case VarEnum.VT_UI8:
return _ulong;
case VarEnum.VT_R4:
return _float;
case VarEnum.VT_R8:
return _double;
case VarEnum.VT_BOOL:
return _int32 == -1;
case VarEnum.VT_ERROR:
return _long;
case VarEnum.VT_CY:
return _decimal;
case VarEnum.VT_DATE:
return DateTime.FromOADate(_double);
case VarEnum.VT_FILETIME:
return DateTime.FromFileTime(_long);
case VarEnum.VT_BSTR:
return Marshal.PtrToStringBSTR(_ptr);
case VarEnum.VT_BLOB:
return GetBlobData();
case VarEnum.VT_LPSTR:
return Marshal.PtrToStringAnsi(_ptr);
case VarEnum.VT_LPWSTR:
return Marshal.PtrToStringUni(_ptr);
case VarEnum.VT_UNKNOWN:
return Marshal.GetObjectForIUnknown(_ptr);
case VarEnum.VT_DISPATCH:
return Marshal.GetObjectForIUnknown(_ptr);
case VarEnum.VT_DECIMAL:
return _decimal;
case VarEnum.VT_ARRAY | VarEnum.VT_UNKNOWN:
return CrackSingleDimSafeArray(_ptr);
case (VarEnum.VT_VECTOR | VarEnum.VT_LPWSTR):
return GetVector<string>();
case (VarEnum.VT_VECTOR | VarEnum.VT_I2):
return GetVector<Int16>();
case (VarEnum.VT_VECTOR | VarEnum.VT_UI2):
return GetVector<UInt16>();
case (VarEnum.VT_VECTOR | VarEnum.VT_I4):
return GetVector<Int32>();
case (VarEnum.VT_VECTOR | VarEnum.VT_UI4):
return GetVector<UInt32>();
case (VarEnum.VT_VECTOR | VarEnum.VT_I8):
return GetVector<Int64>();
case (VarEnum.VT_VECTOR | VarEnum.VT_UI8):
return GetVector<UInt64>();
case (VarEnum.VT_VECTOR|VarEnum.VT_R4):
return GetVector<float>();
case (VarEnum.VT_VECTOR | VarEnum.VT_R8):
return GetVector<Double>();
case (VarEnum.VT_VECTOR | VarEnum.VT_BOOL):
return GetVector<Boolean>();
case (VarEnum.VT_VECTOR | VarEnum.VT_FILETIME):
return GetVector<DateTime>();
case (VarEnum.VT_VECTOR | VarEnum.VT_DECIMAL):
return GetVector<Decimal>();
default:
// if the value cannot be marshaled
return null;
}
}
}
#endregion
#region Private Methods
private static long GetFileTimeAsLong(ref System.Runtime.InteropServices.ComTypes.FILETIME val)
{
return (((long)val.dwHighDateTime) << 32) + val.dwLowDateTime;
}
private static System.Runtime.InteropServices.ComTypes.FILETIME DateTimeToFileTime(DateTime value)
{
long hFT = value.ToFileTime();
System.Runtime.InteropServices.ComTypes.FILETIME ft =
new System.Runtime.InteropServices.ComTypes.FILETIME();
ft.dwLowDateTime = (int)(hFT & 0xFFFFFFFF);
ft.dwHighDateTime = (int)(hFT >> 32);
return ft;
}
private object GetBlobData()
{
byte[] blobData = new byte[_int32];
IntPtr pBlobData = _ptr2;
Marshal.Copy(pBlobData, blobData, 0, _int32);
return blobData;
}
private Array GetVector<T>()
{
int count = PropVariantNativeMethods.PropVariantGetElementCount(this);
if (count <= 0) { return null; }
lock (_padlock)
{
if (_vectorActions == null)
{
_vectorActions = GenerateVectorActions();
}
}
Action<PropVariant, Array, uint> action;
if (!_vectorActions.TryGetValue(typeof(T), out action))
{
throw new InvalidCastException(LocalizedMessages.PropVariantUnsupportedType);
}
Array array = new T[count];
for (uint i = 0; i < count; i++)
{
action(this, array, i);
}
return array;
}
private static Array CrackSingleDimSafeArray(IntPtr psa)
{
uint cDims = PropVariantNativeMethods.SafeArrayGetDim(psa);
if (cDims != 1)
throw new ArgumentException(LocalizedMessages.PropVariantMultiDimArray, "psa");
int lBound = PropVariantNativeMethods.SafeArrayGetLBound(psa, 1U);
int uBound = PropVariantNativeMethods.SafeArrayGetUBound(psa, 1U);
int n = uBound - lBound + 1; // uBound is inclusive
object[] array = new object[n];
for (int i = lBound; i <= uBound; ++i)
{
array[i] = PropVariantNativeMethods.SafeArrayGetElement(psa, ref i);
}
return array;
}
#endregion
#region IDisposable Members
/// <summary>
/// Disposes the object, calls the clear function.
/// </summary>
public void Dispose()
{
PropVariantNativeMethods.PropVariantClear(this);
GC.SuppressFinalize(this);
}
/// <summary>
/// Finalizer
/// </summary>
~PropVariant()
{
Dispose();
}
#endregion
/// <summary>
/// Provides an simple string representation of the contained data and type.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
"{0}: {1}", Value, VarType.ToString());
}
}
}

Просмотреть файл

@ -0,0 +1,107 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell.PropertySystem
{
internal static class PropVariantNativeMethods
{
[DllImport("Ole32.dll", PreserveSig = false)] // returns hresult
internal extern static void PropVariantClear([In, Out] PropVariant pvar);
[DllImport("OleAut32.dll", PreserveSig = true)] // psa is actually returned, not hresult
internal extern static IntPtr SafeArrayCreateVector(ushort vt, int lowerBound, uint cElems);
[DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
internal extern static IntPtr SafeArrayAccessData(IntPtr psa);
[DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
internal extern static void SafeArrayUnaccessData(IntPtr psa);
[DllImport("OleAut32.dll", PreserveSig = true)] // retuns uint32
internal extern static uint SafeArrayGetDim(IntPtr psa);
[DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
internal extern static int SafeArrayGetLBound(IntPtr psa, uint nDim);
[DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
internal extern static int SafeArrayGetUBound(IntPtr psa, uint nDim);
// This decl for SafeArrayGetElement is only valid for cDims==1!
[DllImport("OleAut32.dll", PreserveSig = false)] // returns hresult
[return: MarshalAs(UnmanagedType.IUnknown)]
internal extern static object SafeArrayGetElement(IntPtr psa, ref int rgIndices);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromPropVariantVectorElem([In] PropVariant propvarIn, uint iElem, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromFileTime([In] ref System.Runtime.InteropServices.ComTypes.FILETIME pftIn, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.I4)]
internal static extern int PropVariantGetElementCount([In] PropVariant propVar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetBooleanElem([In] PropVariant propVar, [In]uint iElem, [Out, MarshalAs(UnmanagedType.Bool)] out bool pfVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetInt16Elem([In] PropVariant propVar, [In] uint iElem, [Out] out short pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetUInt16Elem([In] PropVariant propVar, [In] uint iElem, [Out] out ushort pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetInt32Elem([In] PropVariant propVar, [In] uint iElem, [Out] out int pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetUInt32Elem([In] PropVariant propVar, [In] uint iElem, [Out] out uint pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetInt64Elem([In] PropVariant propVar, [In] uint iElem, [Out] out Int64 pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetUInt64Elem([In] PropVariant propVar, [In] uint iElem, [Out] out UInt64 pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetDoubleElem([In] PropVariant propVar, [In] uint iElem, [Out] out double pnVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetFileTimeElem([In] PropVariant propVar, [In] uint iElem, [Out, MarshalAs(UnmanagedType.Struct)] out System.Runtime.InteropServices.ComTypes.FILETIME pftVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void PropVariantGetStringElem([In] PropVariant propVar, [In] uint iElem, [MarshalAs(UnmanagedType.LPWStr)] ref string ppszVal);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromBooleanVector([In, MarshalAs(UnmanagedType.LPArray)] bool[] prgf, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromInt16Vector([In, Out] Int16[] prgn, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromUInt16Vector([In, Out] UInt16[] prgn, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromInt32Vector([In, Out] Int32[] prgn, uint cElems, [Out] PropVariant propVar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromUInt32Vector([In, Out] UInt32[] prgn, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromInt64Vector([In, Out] Int64[] prgn, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromUInt64Vector([In, Out] UInt64[] prgn, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromDoubleVector([In, Out] double[] prgn, uint cElems, [Out] PropVariant propvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromFileTimeVector([In, Out] System.Runtime.InteropServices.ComTypes.FILETIME[] prgft, uint cElems, [Out] PropVariant ppropvar);
[DllImport("propsys.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = false)]
internal static extern void InitPropVariantFromStringVector([In, Out] string[] prgsz, uint cElems, [Out] PropVariant ppropvar);
}
}

Просмотреть файл

@ -0,0 +1,150 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Shell.PropertySystem
{
/// <summary>
/// Defines a unique key for a Shell Property
/// </summary>
[StructLayout(LayoutKind.Sequential, Pack = 4)]
public struct PropertyKey : IEquatable<PropertyKey>
{
#region Private Fields
private Guid formatId;
private Int32 propertyId;
#endregion
#region Public Properties
/// <summary>
/// A unique GUID for the property
/// </summary>
public Guid FormatId
{
get
{
return formatId;
}
}
/// <summary>
/// Property identifier (PID)
/// </summary>
public Int32 PropertyId
{
get
{
return propertyId;
}
}
#endregion
#region Public Construction
/// <summary>
/// PropertyKey Constructor
/// </summary>
/// <param name="formatId">A unique GUID for the property</param>
/// <param name="propertyId">Property identifier (PID)</param>
public PropertyKey(Guid formatId, Int32 propertyId)
{
this.formatId = formatId;
this.propertyId = propertyId;
}
/// <summary>
/// PropertyKey Constructor
/// </summary>
/// <param name="formatId">A string represenstion of a GUID for the property</param>
/// <param name="propertyId">Property identifier (PID)</param>
public PropertyKey(string formatId, Int32 propertyId)
{
this.formatId = new Guid(formatId);
this.propertyId = propertyId;
}
#endregion
#region IEquatable<PropertyKey> Members
/// <summary>
/// Returns whether this object is equal to another. This is vital for performance of value types.
/// </summary>
/// <param name="other">The object to compare against.</param>
/// <returns>Equality result.</returns>
public bool Equals(PropertyKey other)
{
return other.Equals((object)this);
}
#endregion
#region equality and hashing
/// <summary>
/// Returns the hash code of the object. This is vital for performance of value types.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
return formatId.GetHashCode() ^ propertyId;
}
/// <summary>
/// Returns whether this object is equal to another. This is vital for performance of value types.
/// </summary>
/// <param name="obj">The object to compare against.</param>
/// <returns>Equality result.</returns>
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (!(obj is PropertyKey))
return false;
PropertyKey other = (PropertyKey)obj;
return other.formatId.Equals(formatId) && (other.propertyId == propertyId);
}
/// <summary>
/// Implements the == (equality) operator.
/// </summary>
/// <param name="propKey1">First property key to compare.</param>
/// <param name="propKey2">Second property key to compare.</param>
/// <returns>true if object a equals object b. false otherwise.</returns>
public static bool operator ==(PropertyKey propKey1, PropertyKey propKey2)
{
return propKey1.Equals(propKey2);
}
/// <summary>
/// Implements the != (inequality) operator.
/// </summary>
/// <param name="propKey1">First property key to compare</param>
/// <param name="propKey2">Second property key to compare.</param>
/// <returns>true if object a does not equal object b. false otherwise.</returns>
public static bool operator !=(PropertyKey propKey1, PropertyKey propKey2)
{
return !propKey1.Equals(propKey2);
}
/// <summary>
/// Override ToString() to provide a user friendly string representation
/// </summary>
/// <returns>String representing the property key</returns>
public override string ToString()
{
return string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.PropertyKeyFormatString,
formatId.ToString("B"), propertyId);
}
#endregion
}
}

675
Core/Resources/LocalizedMessages.Designer.cs сгенерированный Normal file
Просмотреть файл

@ -0,0 +1,675 @@
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Microsoft.WindowsAPICodePack.Resources {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class LocalizedMessages {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal LocalizedMessages() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.WindowsAPICodePack.Resources.LocalizedMessages", typeof(LocalizedMessages).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Failed to register application for restart due to bad parameters..
/// </summary>
internal static string ApplicationRecoverFailedToRegisterForRestartBadParameters {
get {
return ResourceManager.GetString("ApplicationRecoverFailedToRegisterForRestartBadParameters", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Application was not registered for recovery due to bad parameters..
/// </summary>
internal static string ApplicationRecoveryBadParameters {
get {
return ResourceManager.GetString("ApplicationRecoveryBadParameters", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Application failed to register for recovery..
/// </summary>
internal static string ApplicationRecoveryFailedToRegister {
get {
return ResourceManager.GetString("ApplicationRecoveryFailedToRegister", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Application failed to registered for restart..
/// </summary>
internal static string ApplicationRecoveryFailedToRegisterForRestart {
get {
return ResourceManager.GetString("ApplicationRecoveryFailedToRegisterForRestart", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unregister for recovery failed..
/// </summary>
internal static string ApplicationRecoveryFailedToUnregister {
get {
return ResourceManager.GetString("ApplicationRecoveryFailedToUnregister", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unregister for restart failed..
/// </summary>
internal static string ApplicationRecoveryFailedToUnregisterForRestart {
get {
return ResourceManager.GetString("ApplicationRecoveryFailedToUnregisterForRestart", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This method must be called from the registered callback method..
/// </summary>
internal static string ApplicationRecoveryMustBeCalledFromCallback {
get {
return ResourceManager.GetString("ApplicationRecoveryMustBeCalledFromCallback", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ACOnline: {1}{0}Max Charge: {2} mWh{0}Current Charge: {3} mWh{0}Discharge Rate: {4} mWh{0}Estimated Time Remaining: {5}{0}Suggested Critical Battery Charge: {6} mWh{0}Suggested Battery Warning Charge: {7} mWh{0}.
/// </summary>
internal static string BatteryStateStringRepresentation {
get {
return ResourceManager.GetString("BatteryStateStringRepresentation", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cancelable cannot be changed while dialog is showing..
/// </summary>
internal static string CancelableCannotBeChanged {
get {
return ResourceManager.GetString("CancelableCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog caption cannot be changed while dialog is showing..
/// </summary>
internal static string CaptionCannotBeChanged {
get {
return ResourceManager.GetString("CaptionCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to CheckBox text cannot be changed while dialog is showing..
/// </summary>
internal static string CheckBoxCannotBeChanged {
get {
return ResourceManager.GetString("CheckBoxCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Collapsed control text cannot be changed while dialog is showing..
/// </summary>
internal static string CollapsedTextCannotBeChanged {
get {
return ResourceManager.GetString("CollapsedTextCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only supported on Windows 7 or newer..
/// </summary>
internal static string CoreHelpersRunningOn7 {
get {
return ResourceManager.GetString("CoreHelpersRunningOn7", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only supported on Windows Vista or newer..
/// </summary>
internal static string CoreHelpersRunningOnVista {
get {
return ResourceManager.GetString("CoreHelpersRunningOnVista", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Only supported on Windows XP or newer..
/// </summary>
internal static string CoreHelpersRunningOnXp {
get {
return ResourceManager.GetString("CoreHelpersRunningOnXp", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog cannot have more than one control with the same name..
/// </summary>
internal static string DialogCollectionCannotHaveDuplicateNames {
get {
return ResourceManager.GetString("DialogCollectionCannotHaveDuplicateNames", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog control must be removed from current collections first..
/// </summary>
internal static string DialogCollectionControlAlreadyHosted {
get {
return ResourceManager.GetString("DialogCollectionControlAlreadyHosted", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Control name cannot be null or zero length..
/// </summary>
internal static string DialogCollectionControlNameNull {
get {
return ResourceManager.GetString("DialogCollectionControlNameNull", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Modifying controls collection while dialog is showing is not supported..
/// </summary>
internal static string DialogCollectionModifyShowingDialog {
get {
return ResourceManager.GetString("DialogCollectionModifyShowingDialog", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog control name cannot be empty or null..
/// </summary>
internal static string DialogControlNameCannotBeEmpty {
get {
return ResourceManager.GetString("DialogControlNameCannotBeEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog controls cannot be renamed..
/// </summary>
internal static string DialogControlsCannotBeRenamed {
get {
return ResourceManager.GetString("DialogControlsCannotBeRenamed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Application.
/// </summary>
internal static string DialogDefaultCaption {
get {
return ResourceManager.GetString("DialogDefaultCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string DialogDefaultContent {
get {
return ResourceManager.GetString("DialogDefaultContent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string DialogDefaultMainInstruction {
get {
return ResourceManager.GetString("DialogDefaultMainInstruction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expanded information mode cannot be changed while dialog is showing..
/// </summary>
internal static string ExpandedDetailsCannotBeChanged {
get {
return ResourceManager.GetString("ExpandedDetailsCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expanded control label cannot be changed while dialog is showing..
/// </summary>
internal static string ExpandedLabelCannotBeChanged {
get {
return ResourceManager.GetString("ExpandedLabelCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Expanding state of the dialog cannot be changed while dialog is showing..
/// </summary>
internal static string ExpandingStateCannotBeChanged {
get {
return ResourceManager.GetString("ExpandingStateCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Hyperlinks cannot be enabled/disabled while dialog is showing..
/// </summary>
internal static string HyperlinksCannotBetSet {
get {
return ResourceManager.GetString("HyperlinksCannotBetSet", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Reference path is invalid..
/// </summary>
internal static string InvalidReferencePath {
get {
return ResourceManager.GetString("InvalidReferencePath", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The specified event handler has not been registered..
/// </summary>
internal static string MessageManagerHandlerNotRegistered {
get {
return ResourceManager.GetString("MessageManagerHandlerNotRegistered", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An error has occurred in dialog configuration..
/// </summary>
internal static string NativeTaskDialogConfigurationError {
get {
return ResourceManager.GetString("NativeTaskDialogConfigurationError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Invalid arguments to Win32 call..
/// </summary>
internal static string NativeTaskDialogInternalErrorArgs {
get {
return ResourceManager.GetString("NativeTaskDialogInternalErrorArgs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog contents too complex..
/// </summary>
internal static string NativeTaskDialogInternalErrorComplex {
get {
return ResourceManager.GetString("NativeTaskDialogInternalErrorComplex", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to An unexpected internal error occurred in the Win32 call: {0:x}.
/// </summary>
internal static string NativeTaskDialogInternalErrorUnexpected {
get {
return ResourceManager.GetString("NativeTaskDialogInternalErrorUnexpected", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to TaskDialog feature needs to load version 6 of comctl32.dll but a different version is current loaded in memory..
/// </summary>
internal static string NativeTaskDialogVersionError {
get {
return ResourceManager.GetString("NativeTaskDialogVersionError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog owner cannot be changed while dialog is showing..
/// </summary>
internal static string OwnerCannotBeChanged {
get {
return ResourceManager.GetString("OwnerCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to SetThreadExecutionState call failed..
/// </summary>
internal static string PowerExecutionStateFailed {
get {
return ResourceManager.GetString("PowerExecutionStateFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The caller had insufficient access rights to get the system battery state..
/// </summary>
internal static string PowerInsufficientAccessBatteryState {
get {
return ResourceManager.GetString("PowerInsufficientAccessBatteryState", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to The caller had insufficient access rights to get the system power capabilities..
/// </summary>
internal static string PowerInsufficientAccessCapabilities {
get {
return ResourceManager.GetString("PowerInsufficientAccessCapabilities", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Failed to get active power scheme..
/// </summary>
internal static string PowerManagerActiveSchemeFailed {
get {
return ResourceManager.GetString("PowerManagerActiveSchemeFailed", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Battery is not present on this system..
/// </summary>
internal static string PowerManagerBatteryNotPresent {
get {
return ResourceManager.GetString("PowerManagerBatteryNotPresent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Progress bar cannot be changed while dialog is showing..
/// </summary>
internal static string ProgressBarCannotBeChanged {
get {
return ResourceManager.GetString("ProgressBarCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Progress bar cannot be hosted in multiple dialogs..
/// </summary>
internal static string ProgressBarCannotBeHostedInMultipleDialogs {
get {
return ResourceManager.GetString("ProgressBarCannotBeHostedInMultipleDialogs", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to {0}, {1}.
/// </summary>
internal static string PropertyKeyFormatString {
get {
return ResourceManager.GetString("PropertyKeyFormatString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unable to initialize PropVariant..
/// </summary>
internal static string PropVariantInitializationError {
get {
return ResourceManager.GetString("PropVariantInitializationError", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Multi-dimensional SafeArrays not supported..
/// </summary>
internal static string PropVariantMultiDimArray {
get {
return ResourceManager.GetString("PropVariantMultiDimArray", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to String argument cannot be null or empty..
/// </summary>
internal static string PropVariantNullString {
get {
return ResourceManager.GetString("PropVariantNullString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This Value type is not supported..
/// </summary>
internal static string PropVariantTypeNotSupported {
get {
return ResourceManager.GetString("PropVariantTypeNotSupported", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot be cast to unsupported type..
/// </summary>
internal static string PropVariantUnsupportedType {
get {
return ResourceManager.GetString("PropVariantUnsupportedType", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to delegate: {0}, state: {1}, ping: {2}.
/// </summary>
internal static string RecoverySettingsFormatString {
get {
return ResourceManager.GetString("RecoverySettingsFormatString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to command: {0} restrictions: {1}.
/// </summary>
internal static string RestartSettingsFormatString {
get {
return ResourceManager.GetString("RestartSettingsFormatString", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to StandardButtons cannot be changed while dialog is showing..
/// </summary>
internal static string StandardButtonsCannotBeChanged {
get {
return ResourceManager.GetString("StandardButtonsCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Startup location cannot be changed while dialog is showing..
/// </summary>
internal static string StartupLocationCannotBeChanged {
get {
return ResourceManager.GetString("StartupLocationCannotBeChanged", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Bad button ID in closing event..
/// </summary>
internal static string TaskDialogBadButtonId {
get {
return ResourceManager.GetString("TaskDialogBadButtonId", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Button text must be non-empty..
/// </summary>
internal static string TaskDialogButtonTextEmpty {
get {
return ResourceManager.GetString("TaskDialogButtonTextEmpty", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Check box text must be provided to enable the dialog check box..
/// </summary>
internal static string TaskDialogCheckBoxTextRequiredToEnableCheckBox {
get {
return ResourceManager.GetString("TaskDialogCheckBoxTextRequiredToEnableCheckBox", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Attempting to close a non-showing dialog..
/// </summary>
internal static string TaskDialogCloseNonShowing {
get {
return ResourceManager.GetString("TaskDialogCloseNonShowing", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Application.
/// </summary>
internal static string TaskDialogDefaultCaption {
get {
return ResourceManager.GetString("TaskDialogDefaultCaption", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string TaskDialogDefaultContent {
get {
return ResourceManager.GetString("TaskDialogDefaultContent", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to .
/// </summary>
internal static string TaskDialogDefaultMainInstruction {
get {
return ResourceManager.GetString("TaskDialogDefaultMainInstruction", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Cannot have more than one default button of a given type..
/// </summary>
internal static string TaskDialogOnlyOneDefaultControl {
get {
return ResourceManager.GetString("TaskDialogOnlyOneDefaultControl", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Maximum value provided must be greater than the minimum value..
/// </summary>
internal static string TaskDialogProgressBarMaxValueGreaterThanMin {
get {
return ResourceManager.GetString("TaskDialogProgressBarMaxValueGreaterThanMin", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minimum value provided must be a positive number..
/// </summary>
internal static string TaskDialogProgressBarMinValueGreaterThanZero {
get {
return ResourceManager.GetString("TaskDialogProgressBarMinValueGreaterThanZero", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Minimum value provided must less than the maximum value..
/// </summary>
internal static string TaskDialogProgressBarMinValueLessThanMax {
get {
return ResourceManager.GetString("TaskDialogProgressBarMinValueLessThanMax", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Value provided must be greater than equal to the minimum value and less than the maximum value..
/// </summary>
internal static string TaskDialogProgressBarValueInRange {
get {
return ResourceManager.GetString("TaskDialogProgressBarValueInRange", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog cannot display both non-standard buttons and standard buttons..
/// </summary>
internal static string TaskDialogSupportedButtonsAndButtons {
get {
return ResourceManager.GetString("TaskDialogSupportedButtonsAndButtons", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Dialog cannot display both non-standard buttons and command links..
/// </summary>
internal static string TaskDialogSupportedButtonsAndLinks {
get {
return ResourceManager.GetString("TaskDialogSupportedButtonsAndLinks", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Unknown dialog control type..
/// </summary>
internal static string TaskDialogUnkownControl {
get {
return ResourceManager.GetString("TaskDialogUnkownControl", resourceCulture);
}
}
}
}

Просмотреть файл

@ -0,0 +1,324 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="ApplicationRecoverFailedToRegisterForRestartBadParameters" xml:space="preserve">
<value>Failed to register application for restart due to bad parameters.</value>
</data>
<data name="ApplicationRecoveryBadParameters" xml:space="preserve">
<value>Application was not registered for recovery due to bad parameters.</value>
</data>
<data name="ApplicationRecoveryFailedToRegister" xml:space="preserve">
<value>Application failed to register for recovery.</value>
</data>
<data name="ApplicationRecoveryFailedToRegisterForRestart" xml:space="preserve">
<value>Application failed to registered for restart.</value>
</data>
<data name="ApplicationRecoveryFailedToUnregister" xml:space="preserve">
<value>Unregister for recovery failed.</value>
</data>
<data name="ApplicationRecoveryFailedToUnregisterForRestart" xml:space="preserve">
<value>Unregister for restart failed.</value>
</data>
<data name="ApplicationRecoveryMustBeCalledFromCallback" xml:space="preserve">
<value>This method must be called from the registered callback method.</value>
</data>
<data name="BatteryStateStringRepresentation" xml:space="preserve">
<value>ACOnline: {1}{0}Max Charge: {2} mWh{0}Current Charge: {3} mWh{0}Discharge Rate: {4} mWh{0}Estimated Time Remaining: {5}{0}Suggested Critical Battery Charge: {6} mWh{0}Suggested Battery Warning Charge: {7} mWh{0}</value>
</data>
<data name="CancelableCannotBeChanged" xml:space="preserve">
<value>Cancelable cannot be changed while dialog is showing.</value>
</data>
<data name="CaptionCannotBeChanged" xml:space="preserve">
<value>Dialog caption cannot be changed while dialog is showing.</value>
</data>
<data name="CheckBoxCannotBeChanged" xml:space="preserve">
<value>CheckBox text cannot be changed while dialog is showing.</value>
</data>
<data name="CollapsedTextCannotBeChanged" xml:space="preserve">
<value>Collapsed control text cannot be changed while dialog is showing.</value>
</data>
<data name="CoreHelpersRunningOn7" xml:space="preserve">
<value>Only supported on Windows 7 or newer.</value>
</data>
<data name="CoreHelpersRunningOnVista" xml:space="preserve">
<value>Only supported on Windows Vista or newer.</value>
</data>
<data name="CoreHelpersRunningOnXp" xml:space="preserve">
<value>Only supported on Windows XP or newer.</value>
</data>
<data name="DialogCollectionCannotHaveDuplicateNames" xml:space="preserve">
<value>Dialog cannot have more than one control with the same name.</value>
</data>
<data name="DialogCollectionControlAlreadyHosted" xml:space="preserve">
<value>Dialog control must be removed from current collections first.</value>
</data>
<data name="DialogCollectionControlNameNull" xml:space="preserve">
<value>Control name cannot be null or zero length.</value>
</data>
<data name="DialogCollectionModifyShowingDialog" xml:space="preserve">
<value>Modifying controls collection while dialog is showing is not supported.</value>
</data>
<data name="DialogControlNameCannotBeEmpty" xml:space="preserve">
<value>Dialog control name cannot be empty or null.</value>
</data>
<data name="DialogControlsCannotBeRenamed" xml:space="preserve">
<value>Dialog controls cannot be renamed.</value>
</data>
<data name="DialogDefaultCaption" xml:space="preserve">
<value>Application</value>
</data>
<data name="DialogDefaultContent" xml:space="preserve">
<value />
</data>
<data name="DialogDefaultMainInstruction" xml:space="preserve">
<value />
</data>
<data name="ExpandedDetailsCannotBeChanged" xml:space="preserve">
<value>Expanded information mode cannot be changed while dialog is showing.</value>
</data>
<data name="ExpandedLabelCannotBeChanged" xml:space="preserve">
<value>Expanded control label cannot be changed while dialog is showing.</value>
</data>
<data name="ExpandingStateCannotBeChanged" xml:space="preserve">
<value>Expanding state of the dialog cannot be changed while dialog is showing.</value>
</data>
<data name="HyperlinksCannotBetSet" xml:space="preserve">
<value>Hyperlinks cannot be enabled/disabled while dialog is showing.</value>
</data>
<data name="InvalidReferencePath" xml:space="preserve">
<value>Reference path is invalid.</value>
</data>
<data name="MessageManagerHandlerNotRegistered" xml:space="preserve">
<value>The specified event handler has not been registered.</value>
</data>
<data name="NativeTaskDialogConfigurationError" xml:space="preserve">
<value>An error has occurred in dialog configuration.</value>
</data>
<data name="NativeTaskDialogInternalErrorArgs" xml:space="preserve">
<value>Invalid arguments to Win32 call.</value>
</data>
<data name="NativeTaskDialogInternalErrorComplex" xml:space="preserve">
<value>Dialog contents too complex.</value>
</data>
<data name="NativeTaskDialogInternalErrorUnexpected" xml:space="preserve">
<value>An unexpected internal error occurred in the Win32 call: {0:x}</value>
</data>
<data name="NativeTaskDialogVersionError" xml:space="preserve">
<value>TaskDialog feature needs to load version 6 of comctl32.dll but a different version is current loaded in memory.</value>
</data>
<data name="OwnerCannotBeChanged" xml:space="preserve">
<value>Dialog owner cannot be changed while dialog is showing.</value>
</data>
<data name="PowerExecutionStateFailed" xml:space="preserve">
<value>SetThreadExecutionState call failed.</value>
</data>
<data name="PowerInsufficientAccessBatteryState" xml:space="preserve">
<value>The caller had insufficient access rights to get the system battery state.</value>
</data>
<data name="PowerInsufficientAccessCapabilities" xml:space="preserve">
<value>The caller had insufficient access rights to get the system power capabilities.</value>
</data>
<data name="PowerManagerBatteryNotPresent" xml:space="preserve">
<value>Battery is not present on this system.</value>
</data>
<data name="ProgressBarCannotBeChanged" xml:space="preserve">
<value>Progress bar cannot be changed while dialog is showing.</value>
</data>
<data name="ProgressBarCannotBeHostedInMultipleDialogs" xml:space="preserve">
<value>Progress bar cannot be hosted in multiple dialogs.</value>
</data>
<data name="PropertyKeyFormatString" xml:space="preserve">
<value>{0}, {1}</value>
</data>
<data name="PropVariantMultiDimArray" xml:space="preserve">
<value>Multi-dimensional SafeArrays not supported.</value>
</data>
<data name="PropVariantNullString" xml:space="preserve">
<value>String argument cannot be null or empty.</value>
</data>
<data name="PropVariantTypeNotSupported" xml:space="preserve">
<value>This Value type is not supported.</value>
</data>
<data name="RecoverySettingsFormatString" xml:space="preserve">
<value>delegate: {0}, state: {1}, ping: {2}</value>
</data>
<data name="RestartSettingsFormatString" xml:space="preserve">
<value>command: {0} restrictions: {1}</value>
</data>
<data name="StandardButtonsCannotBeChanged" xml:space="preserve">
<value>StandardButtons cannot be changed while dialog is showing.</value>
</data>
<data name="StartupLocationCannotBeChanged" xml:space="preserve">
<value>Startup location cannot be changed while dialog is showing.</value>
</data>
<data name="TaskDialogBadButtonId" xml:space="preserve">
<value>Bad button ID in closing event.</value>
</data>
<data name="TaskDialogButtonTextEmpty" xml:space="preserve">
<value>Button text must be non-empty.</value>
</data>
<data name="TaskDialogCheckBoxTextRequiredToEnableCheckBox" xml:space="preserve">
<value>Check box text must be provided to enable the dialog check box.</value>
</data>
<data name="TaskDialogCloseNonShowing" xml:space="preserve">
<value>Attempting to close a non-showing dialog.</value>
</data>
<data name="TaskDialogDefaultCaption" xml:space="preserve">
<value>Application</value>
</data>
<data name="TaskDialogDefaultContent" xml:space="preserve">
<value />
</data>
<data name="TaskDialogDefaultMainInstruction" xml:space="preserve">
<value />
</data>
<data name="TaskDialogOnlyOneDefaultControl" xml:space="preserve">
<value>Cannot have more than one default button of a given type.</value>
</data>
<data name="TaskDialogProgressBarMaxValueGreaterThanMin" xml:space="preserve">
<value>Maximum value provided must be greater than the minimum value.</value>
</data>
<data name="TaskDialogProgressBarMinValueGreaterThanZero" xml:space="preserve">
<value>Minimum value provided must be a positive number.</value>
</data>
<data name="TaskDialogProgressBarMinValueLessThanMax" xml:space="preserve">
<value>Minimum value provided must less than the maximum value.</value>
</data>
<data name="TaskDialogProgressBarValueInRange" xml:space="preserve">
<value>Value provided must be greater than equal to the minimum value and less than the maximum value.</value>
</data>
<data name="TaskDialogSupportedButtonsAndButtons" xml:space="preserve">
<value>Dialog cannot display both non-standard buttons and standard buttons.</value>
</data>
<data name="TaskDialogSupportedButtonsAndLinks" xml:space="preserve">
<value>Dialog cannot display both non-standard buttons and command links.</value>
</data>
<data name="TaskDialogUnkownControl" xml:space="preserve">
<value>Unknown dialog control type.</value>
</data>
<data name="PropVariantInitializationError" xml:space="preserve">
<value>Unable to initialize PropVariant.</value>
</data>
<data name="PowerManagerActiveSchemeFailed" xml:space="preserve">
<value>Failed to get active power scheme.</value>
</data>
<data name="PropVariantUnsupportedType" xml:space="preserve">
<value>Cannot be cast to unsupported type.</value>
</data>
</root>

Просмотреть файл

@ -0,0 +1,26 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Safe Icon Handle
/// </summary>
public class SafeIconHandle : ZeroInvalidHandle
{
/// <summary>
/// Release the handle
/// </summary>
/// <returns>true if handled is release successfully, false otherwise</returns>
protected override bool ReleaseHandle()
{
if (CoreNativeMethods.DestroyIcon(handle))
{
return true;
}
else
{
return false;
}
}
}
}

Просмотреть файл

@ -0,0 +1,27 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System.Security.Permissions;
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Safe Region Handle
/// </summary>
public class SafeRegionHandle : ZeroInvalidHandle
{
/// <summary>
/// Release the handle
/// </summary>
/// <returns>true if handled is release successfully, false otherwise</returns>
protected override bool ReleaseHandle()
{
if (CoreNativeMethods.DeleteObject(handle))
{
return true;
}
else
{
return false;
}
}
}
}

Просмотреть файл

@ -0,0 +1,32 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System.Security.Permissions;
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Safe Window Handle
/// </summary>
public class SafeWindowHandle : ZeroInvalidHandle
{
/// <summary>
/// Release the handle
/// </summary>
/// <returns>true if handled is release successfully, false otherwise</returns>
protected override bool ReleaseHandle()
{
if (IsInvalid)
{
return true;
}
if (CoreNativeMethods.DestroyWindow(handle) != 0)
{
return true;
}
else
{
return false;
}
}
}
}

Просмотреть файл

@ -0,0 +1,32 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
namespace MS.WindowsAPICodePack.Internal
{
/// <summary>
/// Base class for Safe handles with Null IntPtr as invalid
/// </summary>
public abstract class ZeroInvalidHandle : SafeHandle
{
/// <summary>
/// Default constructor
/// </summary>
protected ZeroInvalidHandle()
: base(IntPtr.Zero, true)
{
}
/// <summary>
/// Determines if this is a valid handle
/// </summary>
public override bool IsInvalid
{
get { return handle == IntPtr.Zero; }
}
}
}

4
Makefile.am Normal file
Просмотреть файл

@ -0,0 +1,4 @@
SUBDIRS = \
Core \
Shell

Просмотреть файл

@ -0,0 +1,68 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Defines the read-only properties for default shell icon sizes.
/// </summary>
public static class DefaultIconSize
{
/// <summary>
/// The small size property for a 16x16 pixel Shell Icon.
/// </summary>
public static readonly System.Windows.Size Small = new System.Windows.Size(16, 16);
/// <summary>
/// The medium size property for a 32x32 pixel Shell Icon.
/// </summary>
public static readonly System.Windows.Size Medium = new System.Windows.Size(32, 32);
/// <summary>
/// The large size property for a 48x48 pixel Shell Icon.
/// </summary>
public static readonly System.Windows.Size Large = new System.Windows.Size(48, 48);
/// <summary>
/// The extra-large size property for a 256x256 pixel Shell Icon.
/// </summary>
public static readonly System.Windows.Size ExtraLarge = new System.Windows.Size(256, 256);
/// <summary>
/// The maximum size for a Shell Icon, 256x256 pixels.
/// </summary>
public static readonly System.Windows.Size Maximum = new System.Windows.Size(256, 256);
}
/// <summary>
/// Defines the read-only properties for default shell thumbnail sizes.
/// </summary>
public static class DefaultThumbnailSize
{
/// <summary>
/// Gets the small size property for a 32x32 pixel Shell Thumbnail.
/// </summary>
public static readonly System.Windows.Size Small = new System.Windows.Size(32, 32);
/// <summary>
/// Gets the medium size property for a 96x96 pixel Shell Thumbnail.
/// </summary>
public static readonly System.Windows.Size Medium = new System.Windows.Size(96, 96);
/// <summary>
/// Gets the large size property for a 256x256 pixel Shell Thumbnail.
/// </summary>
public static readonly System.Windows.Size Large = new System.Windows.Size(256, 256);
/// <summary>
/// Gets the extra-large size property for a 1024x1024 pixel Shell Thumbnail.
/// </summary>
public static readonly System.Windows.Size ExtraLarge = new System.Windows.Size(1024, 1024);
/// <summary>
/// Maximum size for the Shell Thumbnail, 1024x1024 pixels.
/// </summary>
public static readonly System.Windows.Size Maximum = new System.Windows.Size(1024, 1024);
}
}

Просмотреть файл

@ -0,0 +1,63 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
internal class EnumUnknownClass : IEnumUnknown
{
List<ICondition> conditionList = new List<ICondition>();
int current = -1;
internal EnumUnknownClass(ICondition[] conditions)
{
conditionList.AddRange(conditions);
}
#region IEnumUnknown Members
public HResult Next(uint requestedNumber, ref IntPtr buffer, ref uint fetchedNumber)
{
current++;
if (current < conditionList.Count)
{
buffer = Marshal.GetIUnknownForObject(conditionList[current]);
fetchedNumber = 1;
return HResult.Ok;
}
return HResult.False;
}
public HResult Skip(uint number)
{
int temp = current + (int)number;
if (temp > (conditionList.Count - 1))
{
return HResult.False;
}
current = temp;
return HResult.Ok;
}
public HResult Reset()
{
current = -1;
return HResult.Ok;
}
public HResult Clone(out IEnumUnknown result)
{
result = new EnumUnknownClass(this.conditionList.ToArray());
return HResult.Ok;
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Threading;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Provides extension methods for raising events safely.
/// </summary>
public static class EventHandlerExtensionMethods
{
/// <summary>
/// Safely raises an event using EventArgs.Empty
/// </summary>
/// <param name="eventHandler">EventHandler to raise</param>
/// <param name="sender">Event sender</param>
public static void SafeRaise(this EventHandler eventHandler, object sender)
{
if (eventHandler != null)
{
eventHandler(sender, EventArgs.Empty);
}
}
/// <summary>
/// Safely raises an event.
/// </summary>
/// <typeparam name="T">Type of event args</typeparam>
/// <param name="eventHandler">EventHandler&lt;T&gt; to raise</param>
/// <param name="sender">Event sender</param>
/// <param name="args">Event args</param>
public static void SafeRaise<T>(this EventHandler<T> eventHandler, object sender, T args) where T : EventArgs
{
if (eventHandler != null)
{
eventHandler(sender, args);
}
}
/// <summary>
/// Safely raises an event using EventArgs.Empty
/// </summary>
/// <param name="eventHandler">EventHandler&lt;EventArgs&gt; to raise</param>
/// <param name="sender">Event sender</param>
public static void SafeRaise(this EventHandler<EventArgs> eventHandler, object sender)
{
SafeRaise(eventHandler, sender, EventArgs.Empty);
}
}
}

Просмотреть файл

@ -0,0 +1,168 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using Microsoft.WindowsAPICodePack.Resources;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A refence to an icon resource
/// </summary>
public struct IconReference
{
#region Private members
private string moduleName;
private string referencePath;
static private char[] commaSeparator = new char[] { ',' };
#endregion
/// <summary>
/// Overloaded constructor takes in the module name and resource id for the icon reference.
/// </summary>
/// <param name="moduleName">String specifying the name of an executable file, DLL, or icon file</param>
/// <param name="resourceId">Zero-based index of the icon</param>
public IconReference(string moduleName, int resourceId)
: this()
{
if (string.IsNullOrEmpty(moduleName))
{
throw new ArgumentNullException("moduleName");
}
this.moduleName = moduleName;
ResourceId = resourceId;
referencePath = string.Format(System.Globalization.CultureInfo.InvariantCulture,
"{0},{1}", moduleName, resourceId);
}
/// <summary>
/// Overloaded constructor takes in the module name and resource id separated by a comma.
/// </summary>
/// <param name="refPath">Reference path for the icon consiting of the module name and resource id.</param>
public IconReference(string refPath)
: this()
{
if (string.IsNullOrEmpty(refPath))
{
throw new ArgumentNullException("refPath");
}
string[] refParams = refPath.Split(commaSeparator);
if (refParams.Length != 2 || string.IsNullOrEmpty(refParams[0]) || string.IsNullOrEmpty(refParams[1]))
{
throw new ArgumentException(LocalizedMessages.InvalidReferencePath, "refPath");
}
moduleName = refParams[0];
ResourceId = int.Parse(refParams[1], System.Globalization.CultureInfo.InvariantCulture);
this.referencePath = refPath;
}
/// <summary>
/// String specifying the name of an executable file, DLL, or icon file
/// </summary>
public string ModuleName
{
get
{
return moduleName;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
moduleName = value;
}
}
/// <summary>
/// Zero-based index of the icon
/// </summary>
public int ResourceId { get; set; }
/// <summary>
/// Reference to a specific icon within a EXE, DLL or icon file.
/// </summary>
public string ReferencePath
{
get
{
return referencePath;
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
string[] refParams = value.Split(commaSeparator);
if (refParams.Length != 2 || string.IsNullOrEmpty(refParams[0]) || string.IsNullOrEmpty(refParams[1]))
{
throw new ArgumentException(LocalizedMessages.InvalidReferencePath, "value");
}
ModuleName = refParams[0];
ResourceId = int.Parse(refParams[1], System.Globalization.CultureInfo.InvariantCulture);
referencePath = value;
}
}
/// <summary>
/// Implements the == (equality) operator.
/// </summary>
/// <param name="icon1">First object to compare.</param>
/// <param name="icon2">Second object to compare.</param>
/// <returns>True if icon1 equals icon1; false otherwise.</returns>
public static bool operator ==(IconReference icon1, IconReference icon2)
{
return (icon1.moduleName == icon2.moduleName) &&
(icon1.referencePath == icon2.referencePath) &&
(icon1.ResourceId == icon2.ResourceId);
}
/// <summary>
/// Implements the != (unequality) operator.
/// </summary>
/// <param name="icon1">First object to compare.</param>
/// <param name="icon2">Second object to compare.</param>
/// <returns>True if icon1 does not equals icon1; false otherwise.</returns>
public static bool operator !=(IconReference icon1, IconReference icon2)
{
return !(icon1 == icon2);
}
/// <summary>
/// Determines if this object is equal to another.
/// </summary>
/// <param name="obj">The object to compare</param>
/// <returns>Returns true if the objects are equal; false otherwise.</returns>
public override bool Equals(object obj)
{
if (obj == null || !(obj is IconReference)) { return false; }
return (this == (IconReference)obj);
}
/// <summary>
/// Generates a nearly unique hashcode for this structure.
/// </summary>
/// <returns>A hash code.</returns>
public override int GetHashCode()
{
int hash = this.moduleName.GetHashCode();
hash = hash * 31 + this.referencePath.GetHashCode();
hash = hash * 31 + this.ResourceId.GetHashCode();
return hash;
}
}
}

Просмотреть файл

@ -0,0 +1,78 @@
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A wrapper for the native POINT structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct NativePoint
{
/// <summary>
/// Initialize the NativePoint
/// </summary>
/// <param name="x">The x coordinate of the point.</param>
/// <param name="y">The y coordinate of the point.</param>
public NativePoint(int x, int y)
: this()
{
X = x;
Y = y;
}
/// <summary>
/// The X coordinate of the point
/// </summary>
public int X { get; set; }
/// <summary>
/// The Y coordinate of the point
/// </summary>
public int Y { get; set; }
/// <summary>
/// Determines if two NativePoints are equal.
/// </summary>
/// <param name="first">First NativePoint</param>
/// <param name="second">Second NativePoint</param>
/// <returns>True if first NativePoint is equal to the second; false otherwise.</returns>
public static bool operator ==(NativePoint first, NativePoint second)
{
return first.X == second.X
&& first.Y == second.Y;
}
/// <summary>
/// Determines if two NativePoints are not equal.
/// </summary>
/// <param name="first">First NativePoint</param>
/// <param name="second">Second NativePoint</param>
/// <returns>True if first NativePoint is not equal to the second; false otherwise.</returns>
public static bool operator !=(NativePoint first, NativePoint second)
{
return !(first == second);
}
/// <summary>
/// Determines if this NativePoint is equal to another.
/// </summary>
/// <param name="obj">Another NativePoint to compare</param>
/// <returns>True if this NativePoint is equal obj; false otherwise.</returns>
public override bool Equals(object obj)
{
return (obj != null && obj is NativePoint) ? this == (NativePoint)obj : false;
}
/// <summary>
/// Gets a hash code for the NativePoint.
/// </summary>
/// <returns>Hash code for the NativePoint</returns>
public override int GetHashCode()
{
int hash = X.GetHashCode();
hash = hash * 31 + Y.GetHashCode();
return hash;
}
}
}

Просмотреть файл

@ -0,0 +1,96 @@
using System.Runtime.InteropServices;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A wrapper for a RECT struct
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct NativeRect
{
/// <summary>
/// Position of left edge
/// </summary>
public int Left { get; set; }
/// <summary>
/// Position of top edge
/// </summary>
public int Top { get; set; }
/// <summary>
/// Position of right edge
/// </summary>
public int Right { get; set; }
/// <summary>
/// Position of bottom edge
/// </summary>
public int Bottom { get; set; }
/// <summary>
/// Creates a new NativeRect initialized with supplied values.
/// </summary>
/// <param name="left">Position of left edge</param>
/// <param name="top">Position of top edge</param>
/// <param name="right">Position of right edge</param>
/// <param name="bottom">Position of bottom edge</param>
public NativeRect(int left, int top, int right, int bottom)
: this()
{
Left = left;
Top = top;
Right = right;
Bottom = bottom;
}
/// <summary>
/// Determines if two NativeRects are equal.
/// </summary>
/// <param name="first">First NativeRect</param>
/// <param name="second">Second NativeRect</param>
/// <returns>True if first NativeRect is equal to second; false otherwise.</returns>
public static bool operator ==(NativeRect first, NativeRect second)
{
return first.Left == second.Left
&& first.Top == second.Top
&& first.Right == second.Right
&& first.Bottom == second.Bottom;
}
/// <summary>
/// Determines if two NativeRects are not equal
/// </summary>
/// <param name="first">First NativeRect</param>
/// <param name="second">Second NativeRect</param>
/// <returns>True if first is not equal to second; false otherwise.</returns>
public static bool operator !=(NativeRect first, NativeRect second)
{
return !(first == second);
}
/// <summary>
/// Determines if the NativeRect is equal to another Rect.
/// </summary>
/// <param name="obj">Another NativeRect to compare</param>
/// <returns>True if this NativeRect is equal to the one provided; false otherwise.</returns>
public override bool Equals(object obj)
{
return (obj != null && obj is NativeRect) ? this == (NativeRect)obj : false;
}
/// <summary>
/// Creates a hash code for the NativeRect
/// </summary>
/// <returns>Returns hash code for this NativeRect</returns>
public override int GetHashCode()
{
int hash = Left.GetHashCode();
hash = hash * 31 + Top.GetHashCode();
hash = hash * 31 + Right.GetHashCode();
hash = hash * 31 + Bottom.GetHashCode();
return hash;
}
}
}

Просмотреть файл

@ -0,0 +1,181 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Exposes properties and methods for retrieving information about a search condition.
/// </summary>
public class SearchCondition : IDisposable
{
internal SearchCondition(ICondition nativeSearchCondition)
{
if (nativeSearchCondition == null)
{
throw new ArgumentNullException("nativeSearchCondition");
}
NativeSearchCondition = nativeSearchCondition;
HResult hr = NativeSearchCondition.GetConditionType(out conditionType);
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ShellException(hr);
}
if (ConditionType == SearchConditionType.Leaf)
{
using (PropVariant propVar = new PropVariant())
{
hr = NativeSearchCondition.GetComparisonInfo(out canonicalName, out conditionOperation, propVar);
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ShellException(hr);
}
PropertyValue = propVar.Value.ToString();
}
}
}
internal ICondition NativeSearchCondition { get; set; }
private string canonicalName;
/// <summary>
/// The name of a property to be compared or NULL for an unspecified property.
/// </summary>
public string PropertyCanonicalName
{
get { return canonicalName; }
}
private PropertyKey propertyKey;
private PropertyKey emptyPropertyKey = new PropertyKey();
/// <summary>
/// The property key for the property that is to be compared.
/// </summary>
public PropertyKey PropertyKey
{
get
{
if (propertyKey == emptyPropertyKey)
{
int hr = PropertySystemNativeMethods.PSGetPropertyKeyFromName(PropertyCanonicalName, out propertyKey);
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ShellException(hr);
}
}
return propertyKey;
}
}
/// <summary>
/// A value (in <see cref="System.String"/> format) to which the property is compared.
/// </summary>
public string PropertyValue { get; internal set; }
private SearchConditionOperation conditionOperation = SearchConditionOperation.Implicit;
/// <summary>
/// Search condition operation to be performed on the property/value combination.
/// See <see cref="Microsoft.WindowsAPICodePack.Shell.SearchConditionOperation"/> for more details.
/// </summary>
public SearchConditionOperation ConditionOperation
{
get { return conditionOperation; }
}
private SearchConditionType conditionType = SearchConditionType.Leaf;
/// <summary>
/// Represents the condition type for the given node.
/// </summary>
public SearchConditionType ConditionType
{
get { return conditionType; }
}
/// <summary>
/// Retrieves an array of the sub-conditions.
/// </summary>
public IEnumerable<SearchCondition> GetSubConditions()
{
// Our list that we'll return
List<SearchCondition> subConditionsList = new List<SearchCondition>();
// Get the sub-conditions from the native API
object subConditionObj;
Guid guid = new Guid(ShellIIDGuid.IEnumUnknown);
HResult hr = NativeSearchCondition.GetSubConditions(ref guid, out subConditionObj);
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ShellException(hr);
}
// Convert each ICondition to SearchCondition
if (subConditionObj != null)
{
IEnumUnknown enumUnknown = subConditionObj as IEnumUnknown;
IntPtr buffer = IntPtr.Zero;
uint fetched = 0;
while (hr == HResult.Ok)
{
hr = enumUnknown.Next(1, ref buffer, ref fetched);
if (hr == HResult.Ok && fetched == 1)
{
subConditionsList.Add(new SearchCondition((ICondition)Marshal.GetObjectForIUnknown(buffer)));
}
}
}
return subConditionsList;
}
#region IDisposable Members
/// <summary>
///
/// </summary>
~SearchCondition()
{
Dispose(false);
}
/// <summary>
/// Release the native objects.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Release the native objects.
/// </summary>
/// <param name="disposing"></param>
protected virtual void Dispose(bool disposing)
{
if (NativeSearchCondition != null)
{
Marshal.ReleaseComObject(NativeSearchCondition);
NativeSearchCondition = null;
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,481 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using MS.WindowsAPICodePack.Internal;
using Microsoft.WindowsAPICodePack.Shell.Resources;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Provides methods for creating or resolving a condition tree
/// that was obtained by parsing a query string.
/// </summary>
public static class SearchConditionFactory
{
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and constant value.
/// </summary>
/// <param name="propertyName">The name of a property to be compared, or null for an unspecified property.
/// The locale name of the leaf node is LOCALE_NAME_USER_DEFAULT.</param>
/// <param name="value">The constant value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(string propertyName, string value, SearchConditionOperation operation)
{
using (PropVariant propVar = new PropVariant(value))
{
return CreateLeafCondition(propertyName, propVar, null, operation);
}
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and constant value.
/// Overload method takes a DateTime parameter for the comparison value.
/// </summary>
/// <param name="propertyName">The name of a property to be compared, or null for an unspecified property.
/// The locale name of the leaf node is LOCALE_NAME_USER_DEFAULT.</param>
/// <param name="value">The DateTime value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(string propertyName, DateTime value, SearchConditionOperation operation)
{
using (PropVariant propVar = new PropVariant(value))
{
return CreateLeafCondition(propertyName, propVar, "System.StructuredQuery.CustomProperty.DateTime", operation);
}
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and Integer value.
/// </summary>
/// <param name="propertyName">The name of a property to be compared, or null for an unspecified property.
/// The locale name of the leaf node is LOCALE_NAME_USER_DEFAULT.</param>
/// <param name="value">The Integer value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(string propertyName, int value, SearchConditionOperation operation)
{
using (PropVariant propVar = new PropVariant(value))
{
return CreateLeafCondition(propertyName, propVar, "System.StructuredQuery.CustomProperty.Integer", operation);
}
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and Boolean value.
/// </summary>
/// <param name="propertyName">The name of a property to be compared, or null for an unspecified property.
/// The locale name of the leaf node is LOCALE_NAME_USER_DEFAULT.</param>
/// <param name="value">The Boolean value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(string propertyName, bool value, SearchConditionOperation operation)
{
using (PropVariant propVar = new PropVariant(value))
{
return CreateLeafCondition(propertyName, propVar, "System.StructuredQuery.CustomProperty.Boolean", operation);
}
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and Floating Point value.
/// </summary>
/// <param name="propertyName">The name of a property to be compared, or null for an unspecified property.
/// The locale name of the leaf node is LOCALE_NAME_USER_DEFAULT.</param>
/// <param name="value">The Floating Point value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(string propertyName, double value, SearchConditionOperation operation)
{
using (PropVariant propVar = new PropVariant(value))
{
return CreateLeafCondition(propertyName, propVar, "System.StructuredQuery.CustomProperty.FloatingPoint", operation);
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")]
private static SearchCondition CreateLeafCondition(string propertyName, PropVariant propVar, string valueType, SearchConditionOperation operation)
{
IConditionFactory nativeConditionFactory = null;
SearchCondition condition = null;
try
{
// Same as the native "IConditionFactory:MakeLeaf" method
nativeConditionFactory = (IConditionFactory)new ConditionFactoryCoClass();
ICondition nativeCondition = null;
if (string.IsNullOrEmpty(propertyName) || propertyName.ToUpperInvariant() == "SYSTEM.NULL")
{
propertyName = null;
}
HResult hr = HResult.Fail;
hr = nativeConditionFactory.MakeLeaf(propertyName, operation, valueType,
propVar, null, null, null, false, out nativeCondition);
if (!CoreErrorHelper.Succeeded(hr))
{
throw new ShellException(hr);
}
// Create our search condition and set the various properties.
condition = new SearchCondition(nativeCondition);
}
finally
{
if (nativeConditionFactory != null)
{
Marshal.ReleaseComObject(nativeConditionFactory);
}
}
return condition;
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and constant value.
/// </summary>
/// <param name="propertyKey">The property to be compared.</param>
/// <param name="value">The constant value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(PropertyKey propertyKey, string value, SearchConditionOperation operation)
{
string canonicalName;
PropertySystemNativeMethods.PSGetNameFromPropertyKey(ref propertyKey, out canonicalName);
if (string.IsNullOrEmpty(canonicalName))
{
throw new ArgumentException(LocalizedMessages.SearchConditionFactoryInvalidProperty, "propertyKey");
}
return CreateLeafCondition(canonicalName, value, operation);
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and constant value.
/// Overload method takes a DateTime parameter for the comparison value.
/// </summary>
/// <param name="propertyKey">The property to be compared.</param>
/// <param name="value">The DateTime value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(PropertyKey propertyKey, DateTime value, SearchConditionOperation operation)
{
string canonicalName;
PropertySystemNativeMethods.PSGetNameFromPropertyKey(ref propertyKey, out canonicalName);
if (string.IsNullOrEmpty(canonicalName))
{
throw new ArgumentException(LocalizedMessages.SearchConditionFactoryInvalidProperty, "propertyKey");
}
return CreateLeafCondition(canonicalName, value, operation);
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and Boolean value.
/// Overload method takes a DateTime parameter for the comparison value.
/// </summary>
/// <param name="propertyKey">The property to be compared.</param>
/// <param name="value">The boolean value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(PropertyKey propertyKey, bool value, SearchConditionOperation operation)
{
string canonicalName;
PropertySystemNativeMethods.PSGetNameFromPropertyKey(ref propertyKey, out canonicalName);
if (string.IsNullOrEmpty(canonicalName))
{
throw new ArgumentException(LocalizedMessages.SearchConditionFactoryInvalidProperty, "propertyKey");
}
return CreateLeafCondition(canonicalName, value, operation);
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and Floating Point value.
/// Overload method takes a DateTime parameter for the comparison value.
/// </summary>
/// <param name="propertyKey">The property to be compared.</param>
/// <param name="value">The Floating Point value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(PropertyKey propertyKey, double value, SearchConditionOperation operation)
{
string canonicalName;
PropertySystemNativeMethods.PSGetNameFromPropertyKey(ref propertyKey, out canonicalName);
if (string.IsNullOrEmpty(canonicalName))
{
throw new ArgumentException(LocalizedMessages.SearchConditionFactoryInvalidProperty, "propertyKey");
}
return CreateLeafCondition(canonicalName, value, operation);
}
/// <summary>
/// Creates a leaf condition node that represents a comparison of property value and Integer value.
/// Overload method takes a DateTime parameter for the comparison value.
/// </summary>
/// <param name="propertyKey">The property to be compared.</param>
/// <param name="value">The Integer value against which the property value should be compared.</param>
/// <param name="operation">Specific condition to be used when comparing the actual value and the expected value of the given property</param>
/// <returns>SearchCondition based on the given parameters</returns>
/// <remarks>
/// The search will only work for files that are indexed, as well as the specific properties are indexed. To find
/// the properties that are indexed, look for the specific property's property description and
/// <see cref="P:Microsoft.WindowsAPICodePack.Shell.PropertySystem.ShellPropertyDescription.TypeFlags"/> property for IsQueryable flag.
/// </remarks>
public static SearchCondition CreateLeafCondition(PropertyKey propertyKey, int value, SearchConditionOperation operation)
{
string canonicalName;
PropertySystemNativeMethods.PSGetNameFromPropertyKey(ref propertyKey, out canonicalName);
if (string.IsNullOrEmpty(canonicalName))
{
throw new ArgumentException(LocalizedMessages.SearchConditionFactoryInvalidProperty, "propertyKey");
}
return CreateLeafCondition(canonicalName, value, operation);
}
/// <summary>
/// Creates a condition node that is a logical conjunction ("AND") or disjunction ("OR")
/// of a collection of subconditions.
/// </summary>
/// <param name="conditionType">The SearchConditionType of the condition node.
/// Must be either AndCondition or OrCondition.</param>
/// <param name="simplify">TRUE to logically simplify the result, if possible;
/// then the result will not necessarily to be of the specified kind. FALSE if the result should
/// have exactly the prescribed structure. An application that plans to execute a query based on the
/// condition tree would typically benefit from setting this parameter to TRUE. </param>
/// <param name="conditionNodes">Array of subconditions</param>
/// <returns>New SearchCondition based on the operation</returns>
public static SearchCondition CreateAndOrCondition(SearchConditionType conditionType, bool simplify, params SearchCondition[] conditionNodes)
{
// Same as the native "IConditionFactory:MakeAndOr" method
IConditionFactory nativeConditionFactory = (IConditionFactory)new ConditionFactoryCoClass();
ICondition result = null;
try
{
//
List<ICondition> conditionList = new List<ICondition>();
if (conditionNodes != null)
{
foreach (SearchCondition c in conditionNodes)
{
conditionList.Add(c.NativeSearchCondition);
}
}
IEnumUnknown subConditions = new EnumUnknownClass(conditionList.ToArray());
HResult hr = nativeConditionFactory.MakeAndOr(conditionType, subConditions, simplify, out result);
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
}
finally
{
if (nativeConditionFactory != null)
{
Marshal.ReleaseComObject(nativeConditionFactory);
}
}
return new SearchCondition(result);
}
/// <summary>
/// Creates a condition node that is a logical negation (NOT) of another condition
/// (a subnode of this node).
/// </summary>
/// <param name="conditionToBeNegated">SearchCondition node to be negated.</param>
/// <param name="simplify">True to logically simplify the result if possible; False otherwise.
/// In a query builder scenario, simplyfy should typically be set to false.</param>
/// <returns>New SearchCondition</returns>
public static SearchCondition CreateNotCondition(SearchCondition conditionToBeNegated, bool simplify)
{
if (conditionToBeNegated == null)
{
throw new ArgumentNullException("conditionToBeNegated");
}
// Same as the native "IConditionFactory:MakeNot" method
IConditionFactory nativeConditionFactory = (IConditionFactory)new ConditionFactoryCoClass();
ICondition result;
try
{
HResult hr = nativeConditionFactory.MakeNot(conditionToBeNegated.NativeSearchCondition, simplify, out result);
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
}
finally
{
if (nativeConditionFactory != null)
{
Marshal.ReleaseComObject(nativeConditionFactory);
}
}
return new SearchCondition(result);
}
/// <summary>
/// Parses an input string that contains Structured Query keywords (using Advanced Query Syntax
/// or Natural Query Syntax) and produces a SearchCondition object.
/// </summary>
/// <param name="query">The query to be parsed</param>
/// <returns>Search condition resulting from the query</returns>
/// <remarks>For more information on structured query syntax, visit http://msdn.microsoft.com/en-us/library/bb233500.aspx and
/// http://www.microsoft.com/windows/products/winfamily/desktopsearch/technicalresources/advquery.mspx</remarks>
public static SearchCondition ParseStructuredQuery(string query)
{
return ParseStructuredQuery(query, null);
}
/// <summary>
/// Parses an input string that contains Structured Query keywords (using Advanced Query Syntax
/// or Natural Query Syntax) and produces a SearchCondition object.
/// </summary>
/// <param name="query">The query to be parsed</param>
/// <param name="cultureInfo">The culture used to select the localized language for keywords.</param>
/// <returns>Search condition resulting from the query</returns>
/// <remarks>For more information on structured query syntax, visit http://msdn.microsoft.com/en-us/library/bb233500.aspx and
/// http://www.microsoft.com/windows/products/winfamily/desktopsearch/technicalresources/advquery.mspx</remarks>
public static SearchCondition ParseStructuredQuery(string query, CultureInfo cultureInfo)
{
if (string.IsNullOrEmpty(query))
{
throw new ArgumentNullException("query");
}
IQueryParserManager nativeQueryParserManager = (IQueryParserManager)new QueryParserManagerCoClass();
IQueryParser queryParser = null;
IQuerySolution querySolution = null;
ICondition result = null;
IEntity mainType = null;
SearchCondition searchCondition = null;
try
{
// First, try to create a new IQueryParser using IQueryParserManager
Guid guid = new Guid(ShellIIDGuid.IQueryParser);
HResult hr = nativeQueryParserManager.CreateLoadedParser(
"SystemIndex",
cultureInfo == null ? (ushort)0 : (ushort)cultureInfo.LCID,
ref guid,
out queryParser);
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
if (queryParser != null)
{
// If user specified natural query, set the option on the query parser
using (PropVariant optionValue = new PropVariant(true))
{
hr = queryParser.SetOption(StructuredQuerySingleOption.NaturalSyntax, optionValue);
}
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
// Next, try to parse the query.
// Result would be IQuerySolution that we can use for getting the ICondition and other
// details about the parsed query.
hr = queryParser.Parse(query, null, out querySolution);
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
if (querySolution != null)
{
// Lastly, try to get the ICondition from this parsed query
hr = querySolution.GetQuery(out result, out mainType);
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
}
}
searchCondition = new SearchCondition(result);
return searchCondition;
}
catch
{
if (searchCondition != null) { searchCondition.Dispose(); }
throw;
}
finally
{
if (nativeQueryParserManager != null)
{
Marshal.ReleaseComObject(nativeQueryParserManager);
}
if (queryParser != null)
{
Marshal.ReleaseComObject(queryParser);
}
if (querySolution != null)
{
Marshal.ReleaseComObject(querySolution);
}
if (mainType != null)
{
Marshal.ReleaseComObject(mainType);
}
}
}
}
}

535
Shell/Common/ShellEnums.cs Normal file
Просмотреть файл

@ -0,0 +1,535 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// CommonFileDialog AddPlace locations
/// </summary>
public enum FileDialogAddPlaceLocation
{
/// <summary>
/// At the bottom of the Favorites or Places list.
/// </summary>
Bottom = 0x00000000,
/// <summary>
/// At the top of the Favorites or Places list.
/// </summary>
Top = 0x00000001,
}
/// <summary>
/// One of the values that indicates how the ShellObject DisplayName should look.
/// </summary>
public enum DisplayNameType
{
/// <summary>
/// Returns the display name relative to the desktop.
/// </summary>
Default = 0x00000000,
/// <summary>
/// Returns the parsing name relative to the parent folder.
/// </summary>
RelativeToParent = unchecked((int)0x80018001),
/// <summary>
/// Returns the path relative to the parent folder in a
/// friendly format as displayed in an address bar.
/// </summary>
RelativeToParentAddressBar = unchecked((int)0x8007c001),
/// <summary>
/// Returns the parsing name relative to the desktop.
/// </summary>
RelativeToDesktop = unchecked((int)0x80028000),
/// <summary>
/// Returns the editing name relative to the parent folder.
/// </summary>
RelativeToParentEditing = unchecked((int)0x80031001),
/// <summary>
/// Returns the editing name relative to the desktop.
/// </summary>
RelativeToDesktopEditing = unchecked((int)0x8004c000),
/// <summary>
/// Returns the display name relative to the file system path.
/// </summary>
FileSystemPath = unchecked((int)0x80058000),
/// <summary>
/// Returns the display name relative to a URL.
/// </summary>
Url = unchecked((int)0x80068000),
}
/// <summary>
/// Available Library folder types
/// </summary>
public enum LibraryFolderType
{
/// <summary>
/// General Items
/// </summary>
Generic = 0,
/// <summary>
/// Documents
/// </summary>
Documents,
/// <summary>
/// Music
/// </summary>
Music,
/// <summary>
/// Pictures
/// </summary>
Pictures,
/// <summary>
/// Videos
/// </summary>
Videos
}
/// <summary>
/// Flags controlling the appearance of a window
/// </summary>
public enum WindowShowCommand
{
/// <summary>
/// Hides the window and activates another window.
/// </summary>
Hide = 0,
/// <summary>
/// Activates and displays the window (including restoring
/// it to its original size and position).
/// </summary>
Normal = 1,
/// <summary>
/// Minimizes the window.
/// </summary>
Minimized = 2,
/// <summary>
/// Maximizes the window.
/// </summary>
Maximized = 3,
/// <summary>
/// Similar to <see cref="Normal"/>, except that the window
/// is not activated.
/// </summary>
ShowNoActivate = 4,
/// <summary>
/// Activates the window and displays it in its current size
/// and position.
/// </summary>
Show = 5,
/// <summary>
/// Minimizes the window and activates the next top-level window.
/// </summary>
Minimize = 6,
/// <summary>
/// Minimizes the window and does not activate it.
/// </summary>
ShowMinimizedNoActivate = 7,
/// <summary>
/// Similar to <see cref="Normal"/>, except that the window is not
/// activated.
/// </summary>
ShowNA = 8,
/// <summary>
/// Activates and displays the window, restoring it to its original
/// size and position.
/// </summary>
Restore = 9,
/// <summary>
/// Sets the show state based on the initial value specified when
/// the process was created.
/// </summary>
Default = 10,
/// <summary>
/// Minimizes a window, even if the thread owning the window is not
/// responding. Use this only to minimize windows from a different
/// thread.
/// </summary>
ForceMinimize = 11
}
/// <summary>
/// Provides a set of flags to be used with <see cref="Microsoft.WindowsAPICodePack.Shell.SearchCondition"/>
/// to indicate the operation in <see cref="Microsoft.WindowsAPICodePack.Shell.SearchConditionFactory"/> methods.
/// </summary>
public enum SearchConditionOperation
{
/// <summary>
/// An implicit comparison between the value of the property and the value of the constant.
/// </summary>
Implicit = 0,
/// <summary>
/// The value of the property and the value of the constant must be equal.
/// </summary>
Equal = 1,
/// <summary>
/// The value of the property and the value of the constant must not be equal.
/// </summary>
NotEqual = 2,
/// <summary>
/// The value of the property must be less than the value of the constant.
/// </summary>
LessThan = 3,
/// <summary>
/// The value of the property must be greater than the value of the constant.
/// </summary>
GreaterThan = 4,
/// <summary>
/// The value of the property must be less than or equal to the value of the constant.
/// </summary>
LessThanOrEqual = 5,
/// <summary>
/// The value of the property must be greater than or equal to the value of the constant.
/// </summary>
GreaterThanOrEqual = 6,
/// <summary>
/// The value of the property must begin with the value of the constant.
/// </summary>
ValueStartsWith = 7,
/// <summary>
/// The value of the property must end with the value of the constant.
/// </summary>
ValueEndsWith = 8,
/// <summary>
/// The value of the property must contain the value of the constant.
/// </summary>
ValueContains = 9,
/// <summary>
/// The value of the property must not contain the value of the constant.
/// </summary>
ValueNotContains = 10,
/// <summary>
/// The value of the property must match the value of the constant, where '?'
/// matches any single character and '*' matches any sequence of characters.
/// </summary>
DosWildcards = 11,
/// <summary>
/// The value of the property must contain a word that is the value of the constant.
/// </summary>
WordEqual = 12,
/// <summary>
/// The value of the property must contain a word that begins with the value of the constant.
/// </summary>
WordStartsWith = 13,
/// <summary>
/// The application is free to interpret this in any suitable way.
/// </summary>
ApplicationSpecific = 14
}
/// <summary>
/// Set of flags to be used with <see cref="Microsoft.WindowsAPICodePack.Shell.SearchConditionFactory"/>.
/// </summary>
public enum SearchConditionType
{
/// <summary>
/// Indicates that the values of the subterms are combined by "AND".
/// </summary>
And = 0,
/// <summary>
/// Indicates that the values of the subterms are combined by "OR".
/// </summary>
Or = 1,
/// <summary>
/// Indicates a "NOT" comparison of subterms.
/// </summary>
Not = 2,
/// <summary>
/// Indicates that the node is a comparison between a property and a
/// constant value using a <see cref="Microsoft.WindowsAPICodePack.Shell.SearchConditionOperation"/>.
/// </summary>
Leaf = 3,
}
/// <summary>
/// Used to describe the view mode.
/// </summary>
public enum FolderLogicalViewMode
{
/// <summary>
/// The view is not specified.
/// </summary>
Unspecified = -1,
/// <summary>
/// This should have the same affect as Unspecified.
/// </summary>
None = 0,
/// <summary>
/// The minimum valid enumeration value. Used for validation purposes only.
/// </summary>
First = 1,
/// <summary>
/// Details view.
/// </summary>
Details = 1,
/// <summary>
/// Tiles view.
/// </summary>
Tiles = 2,
/// <summary>
/// Icons view.
/// </summary>
Icons = 3,
/// <summary>
/// Windows 7 and later. List view.
/// </summary>
List = 4,
/// <summary>
/// Windows 7 and later. Content view.
/// </summary>
Content = 5,
/// <summary>
/// The maximum valid enumeration value. Used for validation purposes only.
/// </summary>
Last = 5
}
/// <summary>
/// The direction in which the items are sorted.
/// </summary>
public enum SortDirection
{
/// <summary>
/// A default value for sort direction, this value should not be used;
/// instead use Descending or Ascending.
/// </summary>
Default = 0,
/// <summary>
/// The items are sorted in descending order. Whether the sort is alphabetical, numerical,
/// and so on, is determined by the data type of the column indicated in propkey.
/// </summary>
Descending = -1,
/// <summary>
/// The items are sorted in ascending order. Whether the sort is alphabetical, numerical,
/// and so on, is determined by the data type of the column indicated in propkey.
/// </summary>
Ascending = 1,
}
/// <summary>
/// Provides a set of flags to be used with IQueryParser::SetOption and
/// IQueryParser::GetOption to indicate individual options.
/// </summary>
public enum StructuredQuerySingleOption
{
/// <summary>
/// The value should be VT_LPWSTR and the path to a file containing a schema binary.
/// </summary>
Schema,
/// <summary>
/// The value must be VT_EMPTY (the default) or a VT_UI4 that is an LCID. It is used
/// as the locale of contents (not keywords) in the query to be searched for, when no
/// other information is available. The default value is the current keyboard locale.
/// Retrieving the value always returns a VT_UI4.
/// </summary>
Locale,
/// <summary>
/// This option is used to override the default word breaker used when identifying keywords
/// in queries. The default word breaker is chosen according to the language of the keywords
/// (cf. SQSO_LANGUAGE_KEYWORDS below). When setting this option, the value should be VT_EMPTY
/// for using the default word breaker, or a VT_UNKNOWN with an object supporting
/// the IWordBreaker interface. Retrieving the option always returns a VT_UNKNOWN with an object
/// supporting the IWordBreaker interface.
/// </summary>
WordBreaker,
/// <summary>
/// The value should be VT_EMPTY or VT_BOOL with VARIANT_TRUE to allow natural query
/// syntax (the default) or VT_BOOL with VARIANT_FALSE to allow only advanced query syntax.
/// Retrieving the option always returns a VT_BOOL.
/// This option is now deprecated, use SQSO_SYNTAX.
/// </summary>
NaturalSyntax,
/// <summary>
/// The value should be VT_BOOL with VARIANT_TRUE to generate query expressions
/// as if each word in the query had a star appended to it (unless followed by punctuation
/// other than a parenthesis), or VT_EMPTY or VT_BOOL with VARIANT_FALSE to
/// use the words as they are (the default). A word-wheeling application
/// will generally want to set this option to true.
/// Retrieving the option always returns a VT_BOOL.
/// </summary>
AutomaticWildcard,
/// <summary>
/// Reserved. The value should be VT_EMPTY (the default) or VT_I4.
/// Retrieving the option always returns a VT_I4.
/// </summary>
TraceLevel,
/// <summary>
/// The value must be a VT_UI4 that is a LANGID. It defaults to the default user UI language.
/// </summary>
LanguageKeywords,
/// <summary>
/// The value must be a VT_UI4 that is a STRUCTURED_QUERY_SYNTAX value.
/// It defaults to SQS_NATURAL_QUERY_SYNTAX.
/// </summary>
Syntax,
/// <summary>
/// The value must be a VT_BLOB that is a copy of a TIME_ZONE_INFORMATION structure.
/// It defaults to the current time zone.
/// </summary>
TimeZone,
/// <summary>
/// This setting decides what connector should be assumed between conditions when none is specified.
/// The value must be a VT_UI4 that is a CONDITION_TYPE. Only CT_AND_CONDITION and CT_OR_CONDITION
/// are valid. It defaults to CT_AND_CONDITION.
/// </summary>
ImplicitConnector,
/// <summary>
/// This setting decides whether there are special requirements on the case of connector keywords (such
/// as AND or OR). The value must be a VT_UI4 that is a CASE_REQUIREMENT value.
/// It defaults to CASE_REQUIREMENT_UPPER_IF_AQS.
/// </summary>
ConnectorCase,
}
/// <summary>
/// Provides a set of flags to be used with IQueryParser::SetMultiOption
/// to indicate individual options.
/// </summary>
public enum StructuredQueryMultipleOption
{
/// <summary>
/// The key should be property name P. The value should be a
/// VT_UNKNOWN with an IEnumVARIANT which has two values: a VT_BSTR that is another
/// property name Q and a VT_I4 that is a CONDITION_OPERATION cop. A predicate with
/// property name P, some operation and a value V will then be replaced by a predicate
/// with property name Q, operation cop and value V before further processing happens.
/// </summary>
VirtualProperty,
/// <summary>
/// The key should be a value type name V. The value should be a
/// VT_LPWSTR with a property name P. A predicate with no property name and a value of type
/// V (or any subtype of V) will then use property P.
/// </summary>
DefaultProperty,
/// <summary>
/// The key should be a value type name V. The value should be a
/// VT_UNKNOWN with a IConditionGenerator G. The GenerateForLeaf method of
/// G will then be applied to any predicate with value type V and if it returns a query
/// expression, that will be used. If it returns NULL, normal processing will be used
/// instead.
/// </summary>
GeneratorForType,
/// <summary>
/// The key should be a property name P. The value should be a VT_VECTOR|VT_LPWSTR,
/// where each string is a property name. The count must be at least one. This "map" will be
/// added to those of the loaded schema and used during resolution. A second call with the
/// same key will replace the current map. If the value is VT_NULL, the map will be removed.
/// </summary>
MapProperty,
}
/// <summary>
/// Used by IQueryParserManager::SetOption to set parsing options.
/// This can be used to specify schemas and localization options.
/// </summary>
public enum QueryParserManagerOption
{
/// <summary>
/// A VT_LPWSTR containing the name of the file that contains the schema binary.
/// The default value is StructuredQuerySchema.bin for the SystemIndex catalog
/// and StructuredQuerySchemaTrivial.bin for the trivial catalog.
/// </summary>
SchemaBinaryName = 0,
/// <summary>
/// Either a VT_BOOL or a VT_LPWSTR. If the value is a VT_BOOL and is FALSE,
/// a pre-localized schema will not be used. If the value is a VT_BOOL and is TRUE,
/// IQueryParserManager will use the pre-localized schema binary in
/// "%ALLUSERSPROFILE%\Microsoft\Windows". If the value is a VT_LPWSTR, the value should
/// contain the full path of the folder in which the pre-localized schema binary can be found.
/// The default value is VT_BOOL with TRUE.
/// </summary>
PreLocalizedSchemaBinaryPath = 1,
/// <summary>
/// A VT_LPWSTR containing the full path to the folder that contains the
/// unlocalized schema binary. The default value is "%SYSTEMROOT%\System32".
/// </summary>
UnlocalizedSchemaBinaryPath = 2,
/// <summary>
/// A VT_LPWSTR containing the full path to the folder that contains the
/// localized schema binary that can be read and written to as needed.
/// The default value is "%LOCALAPPDATA%\Microsoft\Windows".
/// </summary>
LocalizedSchemaBinaryPath = 3,
/// <summary>
/// A VT_BOOL. If TRUE, then the paths for pre-localized and localized binaries
/// have "\(LCID)" appended to them, where language code identifier (LCID) is
/// the decimal locale ID for the localized language. The default is TRUE.
/// </summary>
AppendLCIDToLocalizedPath = 4,
/// <summary>
/// A VT_UNKNOWN with an object supporting ISchemaLocalizerSupport.
/// This object will be used instead of the default localizer support object.
/// </summary>
LocalizerSupport = 5
}
}

Просмотреть файл

@ -0,0 +1,81 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// An exception thrown when an error occurs while dealing with ShellObjects.
/// </summary>
[Serializable]
public class ShellException : ExternalException
{
/// <summary>
/// Default constructor.
/// </summary>
public ShellException() { }
/// <summary>
/// Initializes a new exception using an HResult
/// </summary>
/// <param name="result">HResult error</param>
internal ShellException(HResult result) : this((int)result) { }
/// <summary>
/// Initializes an excpetion with a custom message.
/// </summary>
/// <param name="message">Custom message</param>
public ShellException(string message) : base(message) { }
/// <summary>
/// Initializes an exception with custom message and inner exception.
/// </summary>
/// <param name="message">Custom message</param>
/// <param name="innerException">The original exception that preceded this exception</param>
public ShellException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes an exception with custom message and error code.
/// </summary>
/// <param name="message">Custom message</param>
/// <param name="errorCode">HResult error code</param>
public ShellException(string message, int errorCode) : base(message, errorCode) { }
/// <summary>
/// Initializes an exception with custom message and error code.
/// </summary>
/// <param name="message"></param>
/// <param name="errorCode"></param>
internal ShellException(string message, HResult errorCode) : this(message, (int)errorCode) { }
/// <summary>
/// Initializes an exception with custom message and inner exception.
/// </summary>
/// <param name="errorCode">HRESULT of an operation</param>
public ShellException(int errorCode)
: base(LocalizedMessages.ShellExceptionDefaultText, errorCode)
{
}
/// <summary>
/// Initializes an exception from serialization info and a context.
/// </summary>
/// <param name="info"></param>
/// <param name="context"></param>
protected ShellException(
System.Runtime.Serialization.SerializationInfo info,
System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
}
}

64
Shell/Common/ShellFile.cs Normal file
Просмотреть файл

@ -0,0 +1,64 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System.IO;
using Microsoft.WindowsAPICodePack.Shell.Resources;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A file in the Shell Namespace
/// </summary>
public class ShellFile : ShellObject
{
#region Internal Constructor
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
internal ShellFile(string path)
{
// Get the absolute path
string absPath = ShellHelper.GetAbsolutePath(path);
// Make sure this is valid
if (!File.Exists(absPath))
{
throw new FileNotFoundException(
string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.FilePathNotExist, path));
}
ParsingName = absPath;
}
internal ShellFile(IShellItem2 shellItem)
{
nativeShellItem = shellItem;
}
#endregion
#region Public Methods
/// <summary>
/// Constructs a new ShellFile object given a file path
/// </summary>
/// <param name="path">The file or folder path</param>
/// <returns>ShellFile object created using given file path.</returns>
static public ShellFile FromFilePath(string path)
{
return new ShellFile(path);
}
#endregion
#region Public Properties
/// <summary>
/// The path for this file
/// </summary>
virtual public string Path
{
get { return this.ParsingName; }
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,75 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System.IO;
using Microsoft.WindowsAPICodePack.Shell.Resources;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A folder in the Shell Namespace
/// </summary>
public class ShellFileSystemFolder : ShellFolder
{
#region Internal Constructor
internal ShellFileSystemFolder()
{
// Empty
}
internal ShellFileSystemFolder(IShellItem2 shellItem)
{
nativeShellItem = shellItem;
}
#endregion
#region Public Methods
/// <summary>
/// Constructs a new ShellFileSystemFolder object given a folder path
/// </summary>
/// <param name="path">The folder path</param>
/// <remarks>ShellFileSystemFolder created from the given folder path.</remarks>
public static ShellFileSystemFolder FromFolderPath(string path)
{
// Get the absolute path
string absPath = ShellHelper.GetAbsolutePath(path);
// Make sure this is valid
if (!Directory.Exists(absPath))
{
throw new DirectoryNotFoundException(
string.Format(System.Globalization.CultureInfo.InvariantCulture,
LocalizedMessages.FilePathNotExist, path));
}
ShellFileSystemFolder folder = new ShellFileSystemFolder();
try
{
folder.ParsingName = absPath;
return folder;
}
catch
{
folder.Dispose();
throw;
}
}
#endregion
#region Public Properties
/// <summary>
/// The path for this Folder
/// </summary>
public virtual string Path
{
get { return this.ParsingName; }
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,12 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents the base class for all types of folders (filesystem and non filesystem)
/// </summary>
public abstract class ShellFolder : ShellContainer
{
// empty
}
}

Просмотреть файл

@ -0,0 +1,117 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
class ShellFolderItems : IEnumerator<ShellObject>
{
#region Private Fields
private IEnumIDList nativeEnumIdList;
private ShellObject currentItem;
ShellContainer nativeShellFolder;
#endregion
#region Internal Constructor
internal ShellFolderItems(ShellContainer nativeShellFolder)
{
this.nativeShellFolder = nativeShellFolder;
HResult hr = nativeShellFolder.NativeShellFolder.EnumObjects(
IntPtr.Zero,
ShellNativeMethods.ShellFolderEnumerationOptions.Folders | ShellNativeMethods.ShellFolderEnumerationOptions.NonFolders,
out nativeEnumIdList);
if (!CoreErrorHelper.Succeeded(hr))
{
if (hr == HResult.Canceled)
{
throw new System.IO.FileNotFoundException();
}
else
{
throw new ShellException(hr);
}
}
}
#endregion
#region IEnumerator<ShellObject> Members
public ShellObject Current
{
get
{
return currentItem;
}
}
#endregion
#region IDisposable Members
public void Dispose()
{
if (nativeEnumIdList != null)
{
Marshal.ReleaseComObject(nativeEnumIdList);
nativeEnumIdList = null;
}
}
#endregion
#region IEnumerator Members
object IEnumerator.Current
{
get { return currentItem; }
}
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool MoveNext()
{
if (nativeEnumIdList == null) { return false; }
IntPtr item;
uint numItemsReturned;
uint itemsRequested = 1;
HResult hr = nativeEnumIdList.Next(itemsRequested, out item, out numItemsReturned);
if (numItemsReturned < itemsRequested || hr != HResult.Ok) { return false; }
currentItem = ShellObjectFactory.Create(item, nativeShellFolder);
return true;
}
/// <summary>
///
/// </summary>
public void Reset()
{
if (nativeEnumIdList != null)
{
nativeEnumIdList.Reset();
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,91 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A helper class for Shell Objects
/// </summary>
internal static class ShellHelper
{
internal static string GetParsingName(IShellItem shellItem)
{
if (shellItem == null) { return null; }
string path = null;
IntPtr pszPath = IntPtr.Zero;
HResult hr = shellItem.GetDisplayName(ShellNativeMethods.ShellItemDesignNameOptions.DesktopAbsoluteParsing, out pszPath);
if (hr != HResult.Ok && hr != HResult.InvalidArguments)
{
throw new ShellException(LocalizedMessages.ShellHelperGetParsingNameFailed, hr);
}
if (pszPath != IntPtr.Zero)
{
path = Marshal.PtrToStringAuto(pszPath);
Marshal.FreeCoTaskMem(pszPath);
pszPath = IntPtr.Zero;
}
return path;
}
internal static string GetAbsolutePath(string path)
{
if (Uri.IsWellFormedUriString(path, UriKind.Absolute))
{
return path;
}
return Path.GetFullPath((path));
}
internal static PropertyKey ItemTypePropertyKey = new PropertyKey(new Guid("28636AA6-953D-11D2-B5D6-00C04FD918D0"), 11);
internal static string GetItemType(IShellItem2 shellItem)
{
if (shellItem != null)
{
string itemType = null;
HResult hr = shellItem.GetString(ref ItemTypePropertyKey, out itemType);
if (hr == HResult.Ok) { return itemType; }
}
return null;
}
internal static IntPtr PidlFromParsingName(string name)
{
IntPtr pidl;
ShellNativeMethods.ShellFileGetAttributesOptions sfgao;
int retCode = ShellNativeMethods.SHParseDisplayName(
name, IntPtr.Zero, out pidl, (ShellNativeMethods.ShellFileGetAttributesOptions)0,
out sfgao);
return (CoreErrorHelper.Succeeded(retCode) ? pidl : IntPtr.Zero);
}
internal static IntPtr PidlFromShellItem(IShellItem nativeShellItem)
{
IntPtr unknown = Marshal.GetIUnknownForObject(nativeShellItem);
return PidlFromUnknown(unknown);
}
internal static IntPtr PidlFromUnknown(IntPtr unknown)
{
IntPtr pidl;
int retCode = ShellNativeMethods.SHGetIDListFromObject(unknown, out pidl);
return (CoreErrorHelper.Succeeded(retCode) ? pidl : IntPtr.Zero);
}
}
}

Просмотреть файл

@ -0,0 +1,70 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
internal class ShellItemArray : IShellItemArray
{
List<IShellItem> shellItemsList = new List<IShellItem>();
internal ShellItemArray(IShellItem[] shellItems)
{
shellItemsList.AddRange(shellItems);
}
#region IShellItemArray Members
public HResult BindToHandler(IntPtr pbc, ref Guid rbhid, ref Guid riid, out IntPtr ppvOut)
{
throw new NotSupportedException();
}
public HResult GetPropertyStore(int Flags, ref Guid riid, out IntPtr ppv)
{
throw new NotSupportedException();
}
public HResult GetPropertyDescriptionList(ref PropertyKey keyType, ref Guid riid, out IntPtr ppv)
{
throw new NotSupportedException();
}
public HResult GetAttributes(ShellNativeMethods.ShellItemAttributeOptions dwAttribFlags, ShellNativeMethods.ShellFileGetAttributesOptions sfgaoMask, out ShellNativeMethods.ShellFileGetAttributesOptions psfgaoAttribs)
{
throw new NotSupportedException();
}
public HResult GetCount(out uint pdwNumItems)
{
pdwNumItems = (uint)shellItemsList.Count;
return HResult.Ok;
}
public HResult GetItemAt(uint dwIndex, out IShellItem ppsi)
{
int index = (int)dwIndex;
if (index < shellItemsList.Count)
{
ppsi = shellItemsList[index];
return HResult.Ok;
}
else
{
ppsi = null;
return HResult.Fail;
}
}
public HResult EnumItems(out IntPtr ppenumShellItems)
{
throw new NotSupportedException();
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,901 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A Shell Library in the Shell Namespace
/// </summary>
public sealed class ShellLibrary : ShellContainer, IList<ShellFileSystemFolder>
{
#region Private Fields
private INativeShellLibrary nativeShellLibrary;
private IKnownFolder knownFolder;
private static Guid[] FolderTypesGuids =
{
new Guid(ShellKFIDGuid.GenericLibrary),
new Guid(ShellKFIDGuid.DocumentsLibrary),
new Guid(ShellKFIDGuid.MusicLibrary),
new Guid(ShellKFIDGuid.PicturesLibrary),
new Guid(ShellKFIDGuid.VideosLibrary)
};
#endregion
#region Private Constructor
private ShellLibrary()
{
CoreHelpers.ThrowIfNotWin7();
}
//Construct the ShellLibrary object from a native Shell Library
private ShellLibrary(INativeShellLibrary nativeShellLibrary)
: this()
{
this.nativeShellLibrary = nativeShellLibrary;
}
/// <summary>
/// Creates a shell library in the Libraries Known Folder,
/// using the given IKnownFolder
/// </summary>
/// <param name="sourceKnownFolder">KnownFolder from which to create the new Shell Library</param>
/// <param name="isReadOnly">If <B>true</B> , opens the library in read-only mode.</param>
private ShellLibrary(IKnownFolder sourceKnownFolder, bool isReadOnly)
: this()
{
Debug.Assert(sourceKnownFolder != null);
// Keep a reference locally
knownFolder = sourceKnownFolder;
nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
AccessModes flags = isReadOnly ?
AccessModes.Read :
AccessModes.ReadWrite;
// Get the IShellItem2
base.nativeShellItem = ((ShellObject)sourceKnownFolder).NativeShellItem2;
Guid guid = sourceKnownFolder.FolderId;
// Load the library from the IShellItem2
try
{
nativeShellLibrary.LoadLibraryFromKnownFolder(ref guid, flags);
}
catch (InvalidCastException)
{
throw new ArgumentException(LocalizedMessages.ShellLibraryInvalidLibrary, "sourceKnownFolder");
}
catch (NotImplementedException)
{
throw new ArgumentException(LocalizedMessages.ShellLibraryInvalidLibrary, "sourceKnownFolder");
}
}
#endregion
#region Public Constructors
/// <summary>
/// Creates a shell library in the Libraries Known Folder,
/// using the given shell library name.
/// </summary>
/// <param name="libraryName">The name of this library</param>
/// <param name="overwrite">Allow overwriting an existing library; if one exists with the same name</param>
public ShellLibrary(string libraryName, bool overwrite)
: this()
{
if (string.IsNullOrEmpty(libraryName))
{
throw new ArgumentException(LocalizedMessages.ShellLibraryEmptyName, "libraryName");
}
this.Name = libraryName;
Guid guid = new Guid(ShellKFIDGuid.Libraries);
ShellNativeMethods.LibrarySaveOptions flags = overwrite ?
ShellNativeMethods.LibrarySaveOptions.OverrideExisting :
ShellNativeMethods.LibrarySaveOptions.FailIfThere;
nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
nativeShellLibrary.SaveInKnownFolder(ref guid, libraryName, flags, out nativeShellItem);
}
/// <summary>
/// Creates a shell library in a given Known Folder,
/// using the given shell library name.
/// </summary>
/// <param name="libraryName">The name of this library</param>
/// <param name="sourceKnownFolder">The known folder</param>
/// <param name="overwrite">Override an existing library with the same name</param>
public ShellLibrary(string libraryName, IKnownFolder sourceKnownFolder, bool overwrite)
: this()
{
if (string.IsNullOrEmpty(libraryName))
{
throw new ArgumentException(LocalizedMessages.ShellLibraryEmptyName, "libraryName");
}
knownFolder = sourceKnownFolder;
this.Name = libraryName;
Guid guid = knownFolder.FolderId;
ShellNativeMethods.LibrarySaveOptions flags = overwrite ?
ShellNativeMethods.LibrarySaveOptions.OverrideExisting :
ShellNativeMethods.LibrarySaveOptions.FailIfThere;
nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
nativeShellLibrary.SaveInKnownFolder(ref guid, libraryName, flags, out nativeShellItem);
}
/// <summary>
/// Creates a shell library in a given local folder,
/// using the given shell library name.
/// </summary>
/// <param name="libraryName">The name of this library</param>
/// <param name="folderPath">The path to the local folder</param>
/// <param name="overwrite">Override an existing library with the same name</param>
public ShellLibrary(string libraryName, string folderPath, bool overwrite)
: this()
{
if (string.IsNullOrEmpty(libraryName))
{
throw new ArgumentException(LocalizedMessages.ShellLibraryEmptyName, "libraryName");
}
if (!Directory.Exists(folderPath))
{
throw new DirectoryNotFoundException(LocalizedMessages.ShellLibraryFolderNotFound);
}
this.Name = libraryName;
ShellNativeMethods.LibrarySaveOptions flags = overwrite ?
ShellNativeMethods.LibrarySaveOptions.OverrideExisting :
ShellNativeMethods.LibrarySaveOptions.FailIfThere;
Guid guid = new Guid(ShellIIDGuid.IShellItem);
IShellItem shellItemIn;
ShellNativeMethods.SHCreateItemFromParsingName(folderPath, IntPtr.Zero, ref guid, out shellItemIn);
nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
nativeShellLibrary.Save(shellItemIn, libraryName, flags, out nativeShellItem);
}
#endregion
#region Public Properties
/// <summary>
/// The name of the library, every library must
/// have a name
/// </summary>
/// <exception cref="COMException">Will throw if no Icon is set</exception>
public override string Name
{
get
{
if (base.Name == null && NativeShellItem != null)
{
base.Name = System.IO.Path.GetFileNameWithoutExtension(ShellHelper.GetParsingName(NativeShellItem));
}
return base.Name;
}
}
/// <summary>
/// The Resource Reference to the icon.
/// </summary>
public IconReference IconResourceId
{
get
{
string iconRef;
nativeShellLibrary.GetIcon(out iconRef);
return new IconReference(iconRef);
}
set
{
nativeShellLibrary.SetIcon(value.ReferencePath);
nativeShellLibrary.Commit();
}
}
/// <summary>
/// One of predefined Library types
/// </summary>
/// <exception cref="COMException">Will throw if no Library Type is set</exception>
public LibraryFolderType LibraryType
{
get
{
Guid folderTypeGuid;
nativeShellLibrary.GetFolderType(out folderTypeGuid);
return GetFolderTypefromGuid(folderTypeGuid);
}
set
{
Guid guid = FolderTypesGuids[(int)value];
nativeShellLibrary.SetFolderType(ref guid);
nativeShellLibrary.Commit();
}
}
/// <summary>
/// The Guid of the Library type
/// </summary>
/// <exception cref="COMException">Will throw if no Library Type is set</exception>
public Guid LibraryTypeId
{
get
{
Guid folderTypeGuid;
nativeShellLibrary.GetFolderType(out folderTypeGuid);
return folderTypeGuid;
}
}
private static LibraryFolderType GetFolderTypefromGuid(Guid folderTypeGuid)
{
for (int i = 0; i < FolderTypesGuids.Length; i++)
{
if (folderTypeGuid.Equals(FolderTypesGuids[i]))
{
return (LibraryFolderType)i;
}
}
throw new ArgumentOutOfRangeException("folderTypeGuid", LocalizedMessages.ShellLibraryInvalidFolderType);
}
/// <summary>
/// By default, this folder is the first location
/// added to the library. The default save folder
/// is both the default folder where files can
/// be saved, and also where the library XML
/// file will be saved, if no other path is specified
/// </summary>
public string DefaultSaveFolder
{
get
{
Guid guid = new Guid(ShellIIDGuid.IShellItem);
IShellItem saveFolderItem;
nativeShellLibrary.GetDefaultSaveFolder(
ShellNativeMethods.DefaultSaveFolderType.Detect,
ref guid,
out saveFolderItem);
return ShellHelper.GetParsingName(saveFolderItem);
}
set
{
if (string.IsNullOrEmpty(value))
{
throw new ArgumentNullException("value");
}
if (!Directory.Exists(value))
{
throw new DirectoryNotFoundException(LocalizedMessages.ShellLibraryDefaultSaveFolderNotFound);
}
string fullPath = new DirectoryInfo(value).FullName;
Guid guid = new Guid(ShellIIDGuid.IShellItem);
IShellItem saveFolderItem;
ShellNativeMethods.SHCreateItemFromParsingName(fullPath, IntPtr.Zero, ref guid, out saveFolderItem);
nativeShellLibrary.SetDefaultSaveFolder(
ShellNativeMethods.DefaultSaveFolderType.Detect,
saveFolderItem);
nativeShellLibrary.Commit();
}
}
/// <summary>
/// Whether the library will be pinned to the
/// Explorer Navigation Pane
/// </summary>
public bool IsPinnedToNavigationPane
{
get
{
ShellNativeMethods.LibraryOptions flags = ShellNativeMethods.LibraryOptions.PinnedToNavigationPane;
nativeShellLibrary.GetOptions(out flags);
return (
(flags & ShellNativeMethods.LibraryOptions.PinnedToNavigationPane) ==
ShellNativeMethods.LibraryOptions.PinnedToNavigationPane);
}
set
{
ShellNativeMethods.LibraryOptions flags = ShellNativeMethods.LibraryOptions.Default;
if (value)
{
flags |= ShellNativeMethods.LibraryOptions.PinnedToNavigationPane;
}
else
{
flags &= ~ShellNativeMethods.LibraryOptions.PinnedToNavigationPane;
}
nativeShellLibrary.SetOptions(ShellNativeMethods.LibraryOptions.PinnedToNavigationPane, flags);
nativeShellLibrary.Commit();
}
}
#endregion
#region Public Methods
/// <summary>
/// Close the library, and release its associated file system resources
/// </summary>
public void Close()
{
this.Dispose();
}
#endregion
#region Internal Properties
internal const string FileExtension = ".library-ms";
internal override IShellItem NativeShellItem
{
get { return NativeShellItem2; }
}
internal override IShellItem2 NativeShellItem2
{
get { return nativeShellItem; }
}
#endregion
#region Static Shell Library methods
/// <summary>
/// Get a the known folder FOLDERID_Libraries
/// </summary>
public static IKnownFolder LibrariesKnownFolder
{
get
{
CoreHelpers.ThrowIfNotWin7();
return KnownFolderHelper.FromKnownFolderId(new Guid(ShellKFIDGuid.Libraries));
}
}
/// <summary>
/// Load the library using a number of options
/// </summary>
/// <param name="libraryName">The name of the library</param>
/// <param name="isReadOnly">If <B>true</B>, loads the library in read-only mode.</param>
/// <returns>A ShellLibrary Object</returns>
public static ShellLibrary Load(string libraryName, bool isReadOnly)
{
CoreHelpers.ThrowIfNotWin7();
IKnownFolder kf = KnownFolders.Libraries;
string librariesFolderPath = (kf != null) ? kf.Path : string.Empty;
Guid guid = new Guid(ShellIIDGuid.IShellItem);
IShellItem nativeShellItem;
string shellItemPath = System.IO.Path.Combine(librariesFolderPath, libraryName + FileExtension);
int hr = ShellNativeMethods.SHCreateItemFromParsingName(shellItemPath, IntPtr.Zero, ref guid, out nativeShellItem);
if (!CoreErrorHelper.Succeeded(hr))
throw new ShellException(hr);
INativeShellLibrary nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
AccessModes flags = isReadOnly ?
AccessModes.Read :
AccessModes.ReadWrite;
nativeShellLibrary.LoadLibraryFromItem(nativeShellItem, flags);
ShellLibrary library = new ShellLibrary(nativeShellLibrary);
try
{
library.nativeShellItem = (IShellItem2)nativeShellItem;
library.Name = libraryName;
return library;
}
catch
{
library.Dispose();
throw;
}
}
/// <summary>
/// Load the library using a number of options
/// </summary>
/// <param name="libraryName">The name of the library.</param>
/// <param name="folderPath">The path to the library.</param>
/// <param name="isReadOnly">If <B>true</B>, opens the library in read-only mode.</param>
/// <returns>A ShellLibrary Object</returns>
public static ShellLibrary Load(string libraryName, string folderPath, bool isReadOnly)
{
CoreHelpers.ThrowIfNotWin7();
// Create the shell item path
string shellItemPath = System.IO.Path.Combine(folderPath, libraryName + FileExtension);
ShellFile item = ShellFile.FromFilePath(shellItemPath);
IShellItem nativeShellItem = item.NativeShellItem;
INativeShellLibrary nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
AccessModes flags = isReadOnly ?
AccessModes.Read :
AccessModes.ReadWrite;
nativeShellLibrary.LoadLibraryFromItem(nativeShellItem, flags);
ShellLibrary library = new ShellLibrary(nativeShellLibrary);
try
{
library.nativeShellItem = (IShellItem2)nativeShellItem;
library.Name = libraryName;
return library;
}
catch
{
library.Dispose();
throw;
}
}
/// <summary>
/// Load the library using a number of options
/// </summary>
/// <param name="nativeShellItem">IShellItem</param>
/// <param name="isReadOnly">read-only flag</param>
/// <returns>A ShellLibrary Object</returns>
internal static ShellLibrary FromShellItem(IShellItem nativeShellItem, bool isReadOnly)
{
CoreHelpers.ThrowIfNotWin7();
INativeShellLibrary nativeShellLibrary = (INativeShellLibrary)new ShellLibraryCoClass();
AccessModes flags = isReadOnly ?
AccessModes.Read :
AccessModes.ReadWrite;
nativeShellLibrary.LoadLibraryFromItem(nativeShellItem, flags);
ShellLibrary library = new ShellLibrary(nativeShellLibrary);
library.nativeShellItem = (IShellItem2)nativeShellItem;
return library;
}
/// <summary>
/// Load the library using a number of options
/// </summary>
/// <param name="sourceKnownFolder">A known folder.</param>
/// <param name="isReadOnly">If <B>true</B>, opens the library in read-only mode.</param>
/// <returns>A ShellLibrary Object</returns>
public static ShellLibrary Load(IKnownFolder sourceKnownFolder, bool isReadOnly)
{
CoreHelpers.ThrowIfNotWin7();
return new ShellLibrary(sourceKnownFolder, isReadOnly);
}
private static void ShowManageLibraryUI(ShellLibrary shellLibrary, IntPtr windowHandle, string title, string instruction, bool allowAllLocations)
{
int hr = 0;
Thread staWorker = new Thread(() =>
{
hr = ShellNativeMethods.SHShowManageLibraryUI(
shellLibrary.NativeShellItem,
windowHandle,
title,
instruction,
allowAllLocations ?
ShellNativeMethods.LibraryManageDialogOptions.NonIndexableLocationWarning :
ShellNativeMethods.LibraryManageDialogOptions.Default);
});
staWorker.SetApartmentState(ApartmentState.STA);
staWorker.Start();
staWorker.Join();
if (!CoreErrorHelper.Succeeded(hr)) { throw new ShellException(hr); }
}
/// <summary>
/// Shows the library management dialog which enables users to mange the library folders and default save location.
/// </summary>
/// <param name="libraryName">The name of the library</param>
/// <param name="folderPath">The path to the library.</param>
/// <param name="windowHandle">The parent window,or IntPtr.Zero for no parent</param>
/// <param name="title">A title for the library management dialog, or null to use the library name as the title</param>
/// <param name="instruction">An optional help string to display for the library management dialog</param>
/// <param name="allowAllLocations">If true, do not show warning dialogs about locations that cannot be indexed</param>
/// <remarks>If the library is already open in read-write mode, the dialog will not save the changes.</remarks>
public static void ShowManageLibraryUI(string libraryName, string folderPath, IntPtr windowHandle, string title, string instruction, bool allowAllLocations)
{
// this method is not safe for MTA consumption and will blow
// Access Violations if called from an MTA thread so we wrap this
// call up into a Worker thread that performs all operations in a
// single threaded apartment
using (ShellLibrary shellLibrary = ShellLibrary.Load(libraryName, folderPath, true))
{
ShowManageLibraryUI(shellLibrary, windowHandle, title, instruction, allowAllLocations);
}
}
/// <summary>
/// Shows the library management dialog which enables users to mange the library folders and default save location.
/// </summary>
/// <param name="libraryName">The name of the library</param>
/// <param name="windowHandle">The parent window,or IntPtr.Zero for no parent</param>
/// <param name="title">A title for the library management dialog, or null to use the library name as the title</param>
/// <param name="instruction">An optional help string to display for the library management dialog</param>
/// <param name="allowAllLocations">If true, do not show warning dialogs about locations that cannot be indexed</param>
/// <remarks>If the library is already open in read-write mode, the dialog will not save the changes.</remarks>
public static void ShowManageLibraryUI(string libraryName, IntPtr windowHandle, string title, string instruction, bool allowAllLocations)
{
// this method is not safe for MTA consumption and will blow
// Access Violations if called from an MTA thread so we wrap this
// call up into a Worker thread that performs all operations in a
// single threaded apartment
using (ShellLibrary shellLibrary = ShellLibrary.Load(libraryName, true))
{
ShowManageLibraryUI(shellLibrary, windowHandle, title, instruction, allowAllLocations);
}
}
/// <summary>
/// Shows the library management dialog which enables users to mange the library folders and default save location.
/// </summary>
/// <param name="sourceKnownFolder">A known folder.</param>
/// <param name="windowHandle">The parent window,or IntPtr.Zero for no parent</param>
/// <param name="title">A title for the library management dialog, or null to use the library name as the title</param>
/// <param name="instruction">An optional help string to display for the library management dialog</param>
/// <param name="allowAllLocations">If true, do not show warning dialogs about locations that cannot be indexed</param>
/// <remarks>If the library is already open in read-write mode, the dialog will not save the changes.</remarks>
public static void ShowManageLibraryUI(IKnownFolder sourceKnownFolder, IntPtr windowHandle, string title, string instruction, bool allowAllLocations)
{
// this method is not safe for MTA consumption and will blow
// Access Violations if called from an MTA thread so we wrap this
// call up into a Worker thread that performs all operations in a
// single threaded apartment
using (ShellLibrary shellLibrary = ShellLibrary.Load(sourceKnownFolder, true))
{
ShowManageLibraryUI(shellLibrary, windowHandle, title, instruction, allowAllLocations);
}
}
#endregion
#region Collection Members
/// <summary>
/// Add a new FileSystemFolder or SearchConnector
/// </summary>
/// <param name="item">The folder to add to the library.</param>
public void Add(ShellFileSystemFolder item)
{
if (item == null) { throw new ArgumentNullException("item"); }
nativeShellLibrary.AddFolder(item.NativeShellItem);
nativeShellLibrary.Commit();
}
/// <summary>
/// Add an existing folder to this library
/// </summary>
/// <param name="folderPath">The path to the folder to be added to the library.</param>
public void Add(string folderPath)
{
if (!Directory.Exists(folderPath))
{
throw new DirectoryNotFoundException(LocalizedMessages.ShellLibraryFolderNotFound);
}
Add(ShellFileSystemFolder.FromFolderPath(folderPath));
}
/// <summary>
/// Clear all items of this Library
/// </summary>
public void Clear()
{
List<ShellFileSystemFolder> list = ItemsList;
foreach (ShellFileSystemFolder folder in list)
{
nativeShellLibrary.RemoveFolder(folder.NativeShellItem);
}
nativeShellLibrary.Commit();
}
/// <summary>
/// Remove a folder or search connector
/// </summary>
/// <param name="item">The item to remove.</param>
/// <returns><B>true</B> if the item was removed.</returns>
public bool Remove(ShellFileSystemFolder item)
{
if (item == null) { throw new ArgumentNullException("item"); }
try
{
nativeShellLibrary.RemoveFolder(item.NativeShellItem);
nativeShellLibrary.Commit();
}
catch (COMException)
{
return false;
}
return true;
}
/// <summary>
/// Remove a folder or search connector
/// </summary>
/// <param name="folderPath">The path of the item to remove.</param>
/// <returns><B>true</B> if the item was removed.</returns>
public bool Remove(string folderPath)
{
ShellFileSystemFolder item = ShellFileSystemFolder.FromFolderPath(folderPath);
return Remove(item);
}
#endregion
#region Disposable Pattern
/// <summary>
/// Release resources
/// </summary>
/// <param name="disposing">Indicates that this was called from Dispose(), rather than from the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (nativeShellLibrary != null)
{
Marshal.ReleaseComObject(nativeShellLibrary);
nativeShellLibrary = null;
}
base.Dispose(disposing);
}
/// <summary>
/// Release resources
/// </summary>
~ShellLibrary()
{
Dispose(false);
}
#endregion
#region Private Properties
private List<ShellFileSystemFolder> ItemsList
{
get { return GetFolders(); }
}
private List<ShellFileSystemFolder> GetFolders()
{
List<ShellFileSystemFolder> list = new List<ShellFileSystemFolder>();
IShellItemArray itemArray;
Guid shellItemArrayGuid = new Guid(ShellIIDGuid.IShellItemArray);
HResult hr = nativeShellLibrary.GetFolders(ShellNativeMethods.LibraryFolderFilter.AllItems, ref shellItemArrayGuid, out itemArray);
if (!CoreErrorHelper.Succeeded(hr)) { return list; }
uint count;
itemArray.GetCount(out count);
for (uint i = 0; i < count; ++i)
{
IShellItem shellItem;
itemArray.GetItemAt(i, out shellItem);
list.Add(new ShellFileSystemFolder(shellItem as IShellItem2));
}
if (itemArray != null)
{
Marshal.ReleaseComObject(itemArray);
itemArray = null;
}
return list;
}
#endregion
#region IEnumerable<ShellFileSystemFolder> Members
/// <summary>
/// Retrieves the collection enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
new public IEnumerator<ShellFileSystemFolder> GetEnumerator()
{
return ItemsList.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Retrieves the collection enumerator.
/// </summary>
/// <returns>The enumerator.</returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ItemsList.GetEnumerator();
}
#endregion
#region ICollection<ShellFileSystemFolder> Members
/// <summary>
/// Determines if an item with the specified path exists in the collection.
/// </summary>
/// <param name="fullPath">The path of the item.</param>
/// <returns><B>true</B> if the item exists in the collection.</returns>
public bool Contains(string fullPath)
{
if (string.IsNullOrEmpty(fullPath))
{
throw new ArgumentNullException("fullPath");
}
return ItemsList.Any(folder => string.Equals(fullPath, folder.Path, StringComparison.OrdinalIgnoreCase));
}
/// <summary>
/// Determines if a folder exists in the collection.
/// </summary>
/// <param name="item">The folder.</param>
/// <returns><B>true</B>, if the folder exists in the collection.</returns>
public bool Contains(ShellFileSystemFolder item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
return ItemsList.Any(folder => string.Equals(item.Path, folder.Path, StringComparison.OrdinalIgnoreCase));
}
#endregion
#region IList<FileSystemFolder> Members
/// <summary>
/// Searches for the specified FileSystemFolder and returns the zero-based index of the
/// first occurrence within Library list.
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The index of the item in the collection, or -1 if the item does not exist.</returns>
public int IndexOf(ShellFileSystemFolder item)
{
return ItemsList.IndexOf(item);
}
/// <summary>
/// Inserts a FileSystemFolder at the specified index.
/// </summary>
/// <param name="index">The index to insert at.</param>
/// <param name="item">The FileSystemFolder to insert.</param>
void IList<ShellFileSystemFolder>.Insert(int index, ShellFileSystemFolder item)
{
// Index related options are not supported by IShellLibrary doesn't support them.
throw new NotImplementedException();
}
/// <summary>
/// Removes an item at the specified index.
/// </summary>
/// <param name="index">The index to remove.</param>
void IList<ShellFileSystemFolder>.RemoveAt(int index)
{
// Index related options are not supported by IShellLibrary doesn't support them.
throw new NotImplementedException();
}
/// <summary>
/// Retrieves the folder at the specified index
/// </summary>
/// <param name="index">The index of the folder to retrieve.</param>
/// <returns>A folder.</returns>
public ShellFileSystemFolder this[int index]
{
get { return ItemsList[index]; }
set
{
// Index related options are not supported by IShellLibrary
// doesn't support them.
throw new NotImplementedException();
}
}
#endregion
#region ICollection<ShellFileSystemFolder> Members
/// <summary>
/// Copies the collection to an array.
/// </summary>
/// <param name="array">The array to copy to.</param>
/// <param name="arrayIndex">The index in the array at which to start the copy.</param>
void ICollection<ShellFileSystemFolder>.CopyTo(ShellFileSystemFolder[] array, int arrayIndex)
{
throw new NotImplementedException();
}
/// <summary>
/// The count of the items in the list.
/// </summary>
public int Count
{
get { return ItemsList.Count; }
}
/// <summary>
/// Indicates whether this list is read-only or not.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
#endregion
/// <summary>
/// Indicates whether this feature is supported on the current platform.
/// </summary>
new public static bool IsPlatformSupported
{
get
{
// We need Windows 7 onwards ...
return CoreHelpers.RunningOnWin7;
}
}
}
}

143
Shell/Common/ShellLink.cs Normal file
Просмотреть файл

@ -0,0 +1,143 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents a link to existing FileSystem or Virtual item.
/// </summary>
public class ShellLink : ShellObject
{
/// <summary>
/// Path for this file e.g. c:\Windows\file.txt,
/// </summary>
private string _internalPath;
#region Internal Constructors
internal ShellLink(IShellItem2 shellItem)
{
nativeShellItem = shellItem;
}
#endregion
#region Public Properties
/// <summary>
/// The path for this link
/// </summary>
virtual public string Path
{
get
{
if (_internalPath == null && NativeShellItem != null)
{
_internalPath = base.ParsingName;
}
return _internalPath;
}
protected set
{
this._internalPath = value;
}
}
private string internalTargetLocation;
/// <summary>
/// Gets the location to which this link points to.
/// </summary>
public string TargetLocation
{
get
{
if (string.IsNullOrEmpty(internalTargetLocation) && NativeShellItem2 != null)
{
internalTargetLocation = this.Properties.System.Link.TargetParsingPath.Value;
}
return internalTargetLocation;
}
set
{
if (value == null) { return; }
internalTargetLocation = value;
if (NativeShellItem2 != null)
{
this.Properties.System.Link.TargetParsingPath.Value = internalTargetLocation;
}
}
}
/// <summary>
/// Gets the ShellObject to which this link points to.
/// </summary>
public ShellObject TargetShellObject
{
get { return ShellObjectFactory.Create(TargetLocation); }
}
/// <summary>
/// Gets or sets the link's title
/// </summary>
public string Title
{
get
{
if (NativeShellItem2 != null) { return this.Properties.System.Title.Value; }
return null;
}
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (NativeShellItem2 != null)
{
this.Properties.System.Title.Value = value;
}
}
}
private string internalArguments;
/// <summary>
/// Gets the arguments associated with this link.
/// </summary>
public string Arguments
{
get
{
if (string.IsNullOrEmpty(internalArguments) && NativeShellItem2 != null)
{
internalArguments = this.Properties.System.Link.Arguments.Value;
}
return internalArguments;
}
}
private string internalComments;
/// <summary>
/// Gets the comments associated with this link.
/// </summary>
public string Comments
{
get
{
if (string.IsNullOrEmpty(internalComments) && NativeShellItem2 != null)
{
internalComments = this.Properties.System.Comment.Value;
}
return internalComments;
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,25 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents a Non FileSystem folder (e.g. My Computer, Control Panel)
/// </summary>
public class ShellNonFileSystemFolder : ShellFolder
{
#region Internal Constructors
internal ShellNonFileSystemFolder()
{
// Empty
}
internal ShellNonFileSystemFolder(IShellItem2 shellItem)
{
nativeShellItem = shellItem;
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,15 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents a non filesystem item (e.g. virtual items inside Control Panel)
/// </summary>
public class ShellNonFileSystemItem : ShellObject
{
internal ShellNonFileSystemItem(IShellItem2 shellItem)
{
nativeShellItem = shellItem;
}
}
}

532
Shell/Common/ShellObject.cs Normal file
Просмотреть файл

@ -0,0 +1,532 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
using System.Runtime.InteropServices.ComTypes;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// The base class for all Shell objects in Shell Namespace.
/// </summary>
abstract public class ShellObject : IDisposable, IEquatable<ShellObject>
{
#region Public Static Methods
/// <summary>
/// Creates a ShellObject subclass given a parsing name.
/// For file system items, this method will only accept absolute paths.
/// </summary>
/// <param name="parsingName">The parsing name of the object.</param>
/// <returns>A newly constructed ShellObject object.</returns>
public static ShellObject FromParsingName(string parsingName)
{
return ShellObjectFactory.Create(parsingName);
}
/// <summary>
/// Indicates whether this feature is supported on the current platform.
/// </summary>
public static bool IsPlatformSupported
{
get
{
// We need Windows Vista onwards ...
return CoreHelpers.RunningOnVista;
}
}
#endregion
#region Internal Fields
/// <summary>
/// Internal member to keep track of the native IShellItem2
/// </summary>
internal IShellItem2 nativeShellItem;
#endregion
#region Constructors
internal ShellObject()
{
}
internal ShellObject(IShellItem2 shellItem)
{
nativeShellItem = shellItem;
}
#endregion
#region Protected Fields
/// <summary>
/// Parsing name for this Object e.g. c:\Windows\file.txt,
/// or ::{Some Guid}
/// </summary>
private string _internalParsingName;
/// <summary>
/// A friendly name for this object that' suitable for display
/// </summary>
private string _internalName;
/// <summary>
/// PID List (PIDL) for this object
/// </summary>
private IntPtr _internalPIDL = IntPtr.Zero;
#endregion
#region Internal Properties
/// <summary>
/// Return the native ShellFolder object as newer IShellItem2
/// </summary>
/// <exception cref="System.Runtime.InteropServices.ExternalException">If the native object cannot be created.
/// The ErrorCode member will contain the external error code.</exception>
virtual internal IShellItem2 NativeShellItem2
{
get
{
if (nativeShellItem == null && ParsingName != null)
{
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
int retCode = ShellNativeMethods.SHCreateItemFromParsingName(ParsingName, IntPtr.Zero, ref guid, out nativeShellItem);
if (nativeShellItem == null || !CoreErrorHelper.Succeeded(retCode))
{
throw new ShellException(LocalizedMessages.ShellObjectCreationFailed, Marshal.GetExceptionForHR(retCode));
}
}
return nativeShellItem;
}
}
/// <summary>
/// Return the native ShellFolder object
/// </summary>
virtual internal IShellItem NativeShellItem
{
get { return NativeShellItem2; }
}
/// <summary>
/// Gets access to the native IPropertyStore (if one is already
/// created for this item and still valid. This is usually done by the
/// ShellPropertyWriter class. The reference will be set to null
/// when the writer has been closed/commited).
/// </summary>
internal IPropertyStore NativePropertyStore { get; set; }
#endregion
#region Public Methods
/// <summary>
/// Updates the native shell item that maps to this shell object. This is necessary when the shell item
/// changes after the shell object has been created. Without this method call, the retrieval of properties will
/// return stale data.
/// </summary>
/// <param name="bindContext">Bind context object</param>
public void Update(IBindCtx bindContext)
{
HResult hr = HResult.Ok;
if (NativeShellItem2 != null)
{
hr = NativeShellItem2.Update(bindContext);
}
if (CoreErrorHelper.Failed(hr))
{
throw new ShellException(hr);
}
}
#endregion
#region Public Properties
private ShellProperties properties;
/// <summary>
/// Gets an object that allows the manipulation of ShellProperties for this shell item.
/// </summary>
public ShellProperties Properties
{
get
{
if (properties == null)
{
properties = new ShellProperties(this);
}
return properties;
}
}
/// <summary>
/// Gets the parsing name for this ShellItem.
/// </summary>
virtual public string ParsingName
{
get
{
if (_internalParsingName == null && nativeShellItem != null)
{
_internalParsingName = ShellHelper.GetParsingName(nativeShellItem);
}
return _internalParsingName ?? string.Empty;
}
protected set
{
_internalParsingName = value;
}
}
/// <summary>
/// Gets the normal display for this ShellItem.
/// </summary>
virtual public string Name
{
get
{
if (_internalName == null && NativeShellItem != null)
{
IntPtr pszString = IntPtr.Zero;
HResult hr = NativeShellItem.GetDisplayName(ShellNativeMethods.ShellItemDesignNameOptions.Normal, out pszString);
if (hr == HResult.Ok && pszString != IntPtr.Zero)
{
_internalName = Marshal.PtrToStringAuto(pszString);
// Free the string
Marshal.FreeCoTaskMem(pszString);
}
}
return _internalName;
}
protected set
{
this._internalName = value;
}
}
/// <summary>
/// Gets the PID List (PIDL) for this ShellItem.
/// </summary>
internal virtual IntPtr PIDL
{
get
{
// Get teh PIDL for the ShellItem
if (_internalPIDL == IntPtr.Zero && NativeShellItem != null)
{
_internalPIDL = ShellHelper.PidlFromShellItem(NativeShellItem);
}
return _internalPIDL;
}
set
{
this._internalPIDL = value;
}
}
/// <summary>
/// Overrides object.ToString()
/// </summary>
/// <returns>A string representation of the object.</returns>
public override string ToString()
{
return this.Name;
}
/// <summary>
/// Returns the display name of the ShellFolder object. DisplayNameType represents one of the
/// values that indicates how the name should look.
/// See <see cref="Microsoft.WindowsAPICodePack.Shell.DisplayNameType"/>for a list of possible values.
/// </summary>
/// <param name="displayNameType">A disaply name type.</param>
/// <returns>A string.</returns>
public virtual string GetDisplayName(DisplayNameType displayNameType)
{
string returnValue = null;
HResult hr = HResult.Ok;
if (NativeShellItem2 != null)
{
hr = NativeShellItem2.GetDisplayName((ShellNativeMethods.ShellItemDesignNameOptions)displayNameType, out returnValue);
}
if (hr != HResult.Ok)
{
throw new ShellException(LocalizedMessages.ShellObjectCannotGetDisplayName, hr);
}
return returnValue;
}
/// <summary>
/// Gets a value that determines if this ShellObject is a link or shortcut.
/// </summary>
public bool IsLink
{
get
{
try
{
ShellNativeMethods.ShellFileGetAttributesOptions sfgao;
NativeShellItem.GetAttributes(ShellNativeMethods.ShellFileGetAttributesOptions.Link, out sfgao);
return (sfgao & ShellNativeMethods.ShellFileGetAttributesOptions.Link) != 0;
}
catch (FileNotFoundException)
{
return false;
}
catch (NullReferenceException)
{
// NativeShellItem is null
return false;
}
}
}
/// <summary>
/// Gets a value that determines if this ShellObject is a file system object.
/// </summary>
public bool IsFileSystemObject
{
get
{
try
{
ShellNativeMethods.ShellFileGetAttributesOptions sfgao;
NativeShellItem.GetAttributes(ShellNativeMethods.ShellFileGetAttributesOptions.FileSystem, out sfgao);
return (sfgao & ShellNativeMethods.ShellFileGetAttributesOptions.FileSystem) != 0;
}
catch (FileNotFoundException)
{
return false;
}
catch (NullReferenceException)
{
// NativeShellItem is null
return false;
}
}
}
private ShellThumbnail thumbnail;
/// <summary>
/// Gets the thumbnail of the ShellObject.
/// </summary>
public ShellThumbnail Thumbnail
{
get
{
if (thumbnail == null) { thumbnail = new ShellThumbnail(this); }
return thumbnail;
}
}
private ShellObject parentShellObject;
/// <summary>
/// Gets the parent ShellObject.
/// Returns null if the object has no parent, i.e. if this object is the Desktop folder.
/// </summary>
public ShellObject Parent
{
get
{
if (parentShellObject == null && NativeShellItem2 != null)
{
IShellItem parentShellItem;
HResult hr = NativeShellItem2.GetParent(out parentShellItem);
if (hr == HResult.Ok && parentShellItem != null)
{
parentShellObject = ShellObjectFactory.Create(parentShellItem);
}
else if (hr == HResult.NoObject)
{
// Should return null if the parent is desktop
return null;
}
else
{
throw new ShellException(hr);
}
}
return parentShellObject;
}
}
#endregion
#region IDisposable Members
/// <summary>
/// Release the native and managed objects
/// </summary>
/// <param name="disposing">Indicates that this is being called from Dispose(), rather than the finalizer.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_internalName = null;
_internalParsingName = null;
properties = null;
thumbnail = null;
parentShellObject = null;
}
if (properties != null)
{
properties.Dispose();
}
if (_internalPIDL != IntPtr.Zero)
{
ShellNativeMethods.ILFree(_internalPIDL);
_internalPIDL = IntPtr.Zero;
}
if (nativeShellItem != null)
{
Marshal.ReleaseComObject(nativeShellItem);
nativeShellItem = null;
}
if (NativePropertyStore != null)
{
Marshal.ReleaseComObject(NativePropertyStore);
NativePropertyStore = null;
}
}
/// <summary>
/// Release the native objects.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Implement the finalizer.
/// </summary>
~ShellObject()
{
Dispose(false);
}
#endregion
#region equality and hashing
/// <summary>
/// Returns the hash code of the object.
/// </summary>
/// <returns></returns>
public override int GetHashCode()
{
if (!hashValue.HasValue)
{
uint size = ShellNativeMethods.ILGetSize(PIDL);
if (size != 0)
{
byte[] pidlData = new byte[size];
Marshal.Copy(PIDL, pidlData, 0, (int)size);
byte[] hashData = ShellObject.hashProvider.ComputeHash(pidlData);
hashValue = BitConverter.ToInt32(hashData, 0);
}
else
{
hashValue = 0;
}
}
return hashValue.Value;
}
private static MD5CryptoServiceProvider hashProvider = new MD5CryptoServiceProvider();
private int? hashValue;
/// <summary>
/// Determines if two ShellObjects are identical.
/// </summary>
/// <param name="other">The ShellObject to comare this one to.</param>
/// <returns>True if the ShellObjects are equal, false otherwise.</returns>
public bool Equals(ShellObject other)
{
bool areEqual = false;
if (other != null)
{
IShellItem ifirst = this.NativeShellItem;
IShellItem isecond = other.NativeShellItem;
if (ifirst != null && isecond != null)
{
int result = 0;
HResult hr = ifirst.Compare(
isecond, SICHINTF.SICHINT_ALLFIELDS, out result);
areEqual = (hr == HResult.Ok) && (result == 0);
}
}
return areEqual;
}
/// <summary>
/// Returns whether this object is equal to another.
/// </summary>
/// <param name="obj">The object to compare against.</param>
/// <returns>Equality result.</returns>
public override bool Equals(object obj)
{
return this.Equals(obj as ShellObject);
}
/// <summary>
/// Implements the == (equality) operator.
/// </summary>
/// <param name="leftShellObject">First object to compare.</param>
/// <param name="rightShellObject">Second object to compare.</param>
/// <returns>True if leftShellObject equals rightShellObject; false otherwise.</returns>
public static bool operator ==(ShellObject leftShellObject, ShellObject rightShellObject)
{
if ((object)leftShellObject == null)
{
return ((object)rightShellObject == null);
}
return leftShellObject.Equals(rightShellObject);
}
/// <summary>
/// Implements the != (inequality) operator.
/// </summary>
/// <param name="leftShellObject">First object to compare.</param>
/// <param name="rightShellObject">Second object to compare.</param>
/// <returns>True if leftShellObject does not equal leftShellObject; false otherwise.</returns>
public static bool operator !=(ShellObject leftShellObject, ShellObject rightShellObject)
{
return !(leftShellObject == rightShellObject);
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,396 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Shell.Resources;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// An ennumerable list of ShellObjects
/// </summary>
public class ShellObjectCollection : IEnumerable, IDisposable, IList<ShellObject>
{
private List<ShellObject> content = new List<ShellObject>();
bool readOnly;
bool isDisposed;
#region construction/disposal/finialization
/// <summary>
/// Creates a ShellObject collection from an IShellItemArray
/// </summary>
/// <param name="iArray">IShellItemArray pointer</param>
/// <param name="readOnly">Indicates whether the collection shouldbe read-only or not</param>
internal ShellObjectCollection(IShellItemArray iArray, bool readOnly)
{
this.readOnly = readOnly;
if (iArray != null)
{
try
{
uint itemCount = 0;
iArray.GetCount(out itemCount);
content.Capacity = (int)itemCount;
for (uint index = 0; index < itemCount; index++)
{
IShellItem iShellItem = null;
iArray.GetItemAt(index, out iShellItem);
content.Add(ShellObjectFactory.Create(iShellItem));
}
}
finally
{
Marshal.ReleaseComObject(iArray);
}
}
}
/// <summary>
/// Creates a ShellObjectCollection from an IDataObject passed during Drop operation.
/// </summary>
/// <param name="dataObject">An object that implements the IDataObject COM interface.</param>
/// <returns>ShellObjectCollection created from the given IDataObject</returns>
public static ShellObjectCollection FromDataObject(System.Runtime.InteropServices.ComTypes.IDataObject dataObject)
{
IShellItemArray shellItemArray;
Guid iid = new Guid(ShellIIDGuid.IShellItemArray);
ShellNativeMethods.SHCreateShellItemArrayFromDataObject(dataObject, ref iid, out shellItemArray);
return new ShellObjectCollection(shellItemArray, true);
}
/// <summary>
/// Constructs an empty ShellObjectCollection
/// </summary>
public ShellObjectCollection()
{
// Left empty
}
/// <summary>
/// Finalizer
/// </summary>
~ShellObjectCollection()
{
Dispose(false);
}
/// <summary>
/// Standard Dispose pattern
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Standard Dispose patterns
/// </summary>
/// <param name="disposing">Indicates that this is being called from Dispose(), rather than the finalizer.</param>
protected virtual void Dispose(bool disposing)
{
if (isDisposed == false)
{
if (disposing)
{
foreach (ShellObject shellObject in content)
{
shellObject.Dispose();
}
content.Clear();
}
isDisposed = true;
}
}
#endregion
#region implementation
/// <summary>
/// Item count
/// </summary>
public int Count { get { return content.Count; } }
/// <summary>
/// Collection enumeration
/// </summary>
/// <returns></returns>
public System.Collections.IEnumerator GetEnumerator()
{
foreach (ShellObject obj in content)
{
yield return obj;
}
}
/// <summary>
/// Builds the data for the CFSTR_SHELLIDLIST Drag and Clipboard data format from the
/// ShellObjects in the collection.
/// </summary>
/// <returns>A memory stream containing the drag/drop data.</returns>
public MemoryStream BuildShellIDList()
{
if (content.Count == 0)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionEmptyCollection);
}
MemoryStream mstream = new MemoryStream();
try
{
BinaryWriter bwriter = new BinaryWriter(mstream);
// number of IDLs to be written (shell objects + parent folder)
uint itemCount = (uint)(content.Count + 1);
// grab the object IDLs
IntPtr[] idls = new IntPtr[itemCount];
for (int index = 0; index < itemCount; index++)
{
if (index == 0)
{
// Because the ShellObjects passed in may be from anywhere, the
// parent folder reference must be the desktop.
idls[index] = ((ShellObject)KnownFolders.Desktop).PIDL;
}
else
{
idls[index] = content[index - 1].PIDL;
}
}
// calculate offset array (folder IDL + item IDLs)
uint[] offsets = new uint[itemCount + 1];
for (int index = 0; index < itemCount; index++)
{
if (index == 0)
{
// first offset equals size of CIDA header data
offsets[0] = (uint)(sizeof(uint) * (offsets.Length + 1));
}
else
{
offsets[index] = offsets[index - 1] + ShellNativeMethods.ILGetSize(idls[index - 1]);
}
}
// Fill out the CIDA header
//
// typedef struct _IDA {
// UINT cidl; // number of relative IDList
// UINT aoffset[1]; // [0]: folder IDList, [1]-[cidl]: item IDList
// } CIDA, * LPIDA;
//
bwriter.Write(content.Count);
foreach (uint offset in offsets)
{
bwriter.Write(offset);
}
// copy idls
foreach (IntPtr idl in idls)
{
byte[] data = new byte[ShellNativeMethods.ILGetSize(idl)];
Marshal.Copy(idl, data, 0, data.Length);
bwriter.Write(data, 0, data.Length);
}
}
catch
{
mstream.Dispose();
throw;
}
// return CIDA stream
return mstream;
}
#endregion
#region IList<ShellObject> Members
/// <summary>
/// Returns the index of a particualr shell object in the collection
/// </summary>
/// <param name="item">The item to search for.</param>
/// <returns>The index of the item found, or -1 if not found.</returns>
public int IndexOf(ShellObject item)
{
return content.IndexOf(item);
}
/// <summary>
/// Inserts a new shell object into the collection.
/// </summary>
/// <param name="index">The index at which to insert.</param>
/// <param name="item">The item to insert.</param>
public void Insert(int index, ShellObject item)
{
if (readOnly)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionInsertReadOnly);
}
content.Insert(index, item);
}
/// <summary>
/// Removes the specified ShellObject from the collection
/// </summary>
/// <param name="index">The index to remove at.</param>
public void RemoveAt(int index)
{
if (readOnly)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionRemoveReadOnly);
}
content.RemoveAt(index);
}
/// <summary>
/// The collection indexer
/// </summary>
/// <param name="index">The index of the item to retrieve.</param>
/// <returns>The ShellObject at the specified index</returns>
public ShellObject this[int index]
{
get
{
return content[index];
}
set
{
if (readOnly)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionInsertReadOnly);
}
content[index] = value;
}
}
#endregion
#region ICollection<ShellObject> Members
/// <summary>
/// Adds a ShellObject to the collection,
/// </summary>
/// <param name="item">The ShellObject to add.</param>
public void Add(ShellObject item)
{
if (readOnly)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionInsertReadOnly);
}
content.Add(item);
}
/// <summary>
/// Clears the collection of ShellObjects.
/// </summary>
public void Clear()
{
if (readOnly)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionRemoveReadOnly);
}
content.Clear();
}
/// <summary>
/// Determines if the collection contains a particular ShellObject.
/// </summary>
/// <param name="item">The ShellObject.</param>
/// <returns>true, if the ShellObject is in the list, false otherwise.</returns>
public bool Contains(ShellObject item)
{
return content.Contains(item);
}
/// <summary>
/// Copies the ShellObjects in the collection to a ShellObject array.
/// </summary>
/// <param name="array">The destination to copy to.</param>
/// <param name="arrayIndex">The index into the array at which copying will commence.</param>
public void CopyTo(ShellObject[] array, int arrayIndex)
{
if (array == null) { throw new ArgumentNullException("array"); }
if (array.Length < arrayIndex + content.Count)
{
throw new ArgumentException(LocalizedMessages.ShellObjectCollectionArrayTooSmall, "array");
}
for (int index = 0; index < content.Count; index++)
{
array[index + arrayIndex] = content[index];
}
}
/// <summary>
/// Retrieves the number of ShellObjects in the collection
/// </summary>
int ICollection<ShellObject>.Count
{
get
{
return content.Count;
}
}
/// <summary>
/// If true, the contents of the collection are immutable.
/// </summary>
public bool IsReadOnly
{
get
{
return readOnly;
}
}
/// <summary>
/// Removes a particular ShellObject from the list.
/// </summary>
/// <param name="item">The ShellObject to remove.</param>
/// <returns>True if the item could be removed, false otherwise.</returns>
public bool Remove(ShellObject item)
{
if (readOnly)
{
throw new InvalidOperationException(LocalizedMessages.ShellObjectCollectionRemoveReadOnly);
}
return content.Remove(item);
}
#endregion
#region IEnumerable<ShellObject> Members
/// <summary>
/// Allows for enumeration through the list of ShellObjects in the collection.
/// </summary>
/// <returns>The IEnumerator interface to use for enumeration.</returns>
IEnumerator<ShellObject> IEnumerable<ShellObject>.GetEnumerator()
{
foreach (ShellObject obj in content)
{
yield return obj;
}
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,120 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents the base class for all types of Shell "containers". Any class deriving from this class
/// can contain other ShellObjects (e.g. ShellFolder, FileSystemKnownFolder, ShellLibrary, etc)
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "This will complicate the class hierarchy and naming convention used in the Shell area")]
public abstract class ShellContainer : ShellObject, IEnumerable<ShellObject>, IDisposable
{
#region Private Fields
private IShellFolder desktopFolderEnumeration;
private IShellFolder nativeShellFolder;
#endregion
#region Internal Properties
internal IShellFolder NativeShellFolder
{
get
{
if (nativeShellFolder == null)
{
Guid guid = new Guid(ShellIIDGuid.IShellFolder);
Guid handler = new Guid(ShellBHIDGuid.ShellFolderObject);
HResult hr = NativeShellItem.BindToHandler(
IntPtr.Zero, ref handler, ref guid, out nativeShellFolder);
if (CoreErrorHelper.Failed(hr))
{
string str = ShellHelper.GetParsingName(NativeShellItem);
if (str != null && str != Environment.GetFolderPath(Environment.SpecialFolder.Desktop))
{
throw new ShellException(hr);
}
}
}
return nativeShellFolder;
}
}
#endregion
#region Internal Constructor
internal ShellContainer() { }
internal ShellContainer(IShellItem2 shellItem) : base(shellItem) { }
#endregion
#region Disposable Pattern
/// <summary>
/// Release resources
/// </summary>
/// <param name="disposing"><B>True</B> indicates that this is being called from Dispose(), rather than the finalizer.</param>
protected override void Dispose(bool disposing)
{
if (nativeShellFolder != null)
{
Marshal.ReleaseComObject(nativeShellFolder);
nativeShellFolder = null;
}
if (desktopFolderEnumeration != null)
{
Marshal.ReleaseComObject(desktopFolderEnumeration);
desktopFolderEnumeration = null;
}
base.Dispose(disposing);
}
#endregion
#region IEnumerable<ShellObject> Members
/// <summary>
/// Enumerates through contents of the ShellObjectContainer
/// </summary>
/// <returns>Enumerated contents</returns>
public IEnumerator<ShellObject> GetEnumerator()
{
if (NativeShellFolder == null)
{
if (desktopFolderEnumeration == null)
{
ShellNativeMethods.SHGetDesktopFolder(out desktopFolderEnumeration);
}
nativeShellFolder = desktopFolderEnumeration;
}
return new ShellFolderItems(this);
}
#endregion
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new ShellFolderItems(this);
}
#endregion
}
}

Просмотреть файл

@ -0,0 +1,220 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using Microsoft.WindowsAPICodePack.Shell.Resources;
using MS.WindowsAPICodePack.Internal;
using System.Linq;
using System.Threading;
namespace Microsoft.WindowsAPICodePack.Shell
{
internal static class ShellObjectFactory
{
/// <summary>
/// Creates a ShellObject given a native IShellItem interface
/// </summary>
/// <param name="nativeShellItem"></param>
/// <returns>A newly constructed ShellObject object</returns>
internal static ShellObject Create(IShellItem nativeShellItem)
{
// Sanity check
Debug.Assert(nativeShellItem != null, "nativeShellItem should not be null");
// Need to make sure we're running on Vista or higher
if (!CoreHelpers.RunningOnVista)
{
throw new PlatformNotSupportedException(LocalizedMessages.ShellObjectFactoryPlatformNotSupported);
}
// A lot of APIs need IShellItem2, so just keep a copy of it here
IShellItem2 nativeShellItem2 = nativeShellItem as IShellItem2;
// Get the System.ItemType property
string itemType = ShellHelper.GetItemType(nativeShellItem2);
if (!string.IsNullOrEmpty(itemType)) { itemType = itemType.ToUpperInvariant(); }
// Get some IShellItem attributes
ShellNativeMethods.ShellFileGetAttributesOptions sfgao;
nativeShellItem2.GetAttributes(ShellNativeMethods.ShellFileGetAttributesOptions.FileSystem | ShellNativeMethods.ShellFileGetAttributesOptions.Folder, out sfgao);
// Is this item a FileSystem item?
bool isFileSystem = (sfgao & ShellNativeMethods.ShellFileGetAttributesOptions.FileSystem) != 0;
// Is this item a Folder?
bool isFolder = (sfgao & ShellNativeMethods.ShellFileGetAttributesOptions.Folder) != 0;
// Shell Library
ShellLibrary shellLibrary = null;
// Create the right type of ShellObject based on the above information
// 1. First check if this is a Shell Link
if (itemType == ".lnk")
{
return new ShellLink(nativeShellItem2);
}
// 2. Check if this is a container or a single item (entity)
else if (isFolder)
{
// 3. If this is a folder, check for types: Shell Library, Shell Folder or Search Container
if (itemType == ".library-ms" && (shellLibrary = ShellLibrary.FromShellItem(nativeShellItem2, true)) != null)
{
return shellLibrary; // we already created this above while checking for Library
}
else if (itemType == ".searchconnector-ms")
{
return new ShellSearchConnector(nativeShellItem2);
}
else if (itemType == ".search-ms")
{
return new ShellSavedSearchCollection(nativeShellItem2);
}
// 4. It's a ShellFolder
if (isFileSystem)
{
// 5. Is it a (File-System / Non-Virtual) Known Folder
if (!IsVirtualKnownFolder(nativeShellItem2))
{ //needs to check if it is a known folder and not virtual
FileSystemKnownFolder kf = new FileSystemKnownFolder(nativeShellItem2);
return kf;
}
return new ShellFileSystemFolder(nativeShellItem2);
}
// 5. Is it a (Non File-System / Virtual) Known Folder
if (IsVirtualKnownFolder(nativeShellItem2))
{ //needs to check if known folder is virtual
NonFileSystemKnownFolder kf = new NonFileSystemKnownFolder(nativeShellItem2);
return kf;
}
return new ShellNonFileSystemFolder(nativeShellItem2);
}
// 6. If this is an entity (single item), check if its filesystem or not
if (isFileSystem) { return new ShellFile(nativeShellItem2); }
return new ShellNonFileSystemItem(nativeShellItem2);
}
// This is a work around for the STA thread bug. This will execute the call on a non-sta thread, then return the result
private static bool IsVirtualKnownFolder(IShellItem2 nativeShellItem2)
{
IntPtr pidl = IntPtr.Zero;
try
{
IKnownFolderNative nativeFolder = null;
KnownFoldersSafeNativeMethods.NativeFolderDefinition definition = new KnownFoldersSafeNativeMethods.NativeFolderDefinition();
// We found a bug where the enumeration of shell folders was
// not reliable when called from a STA thread - it would return
// different results the first time vs the other times.
//
// This is a work around. We call FindFolderFromIDList on a
// worker MTA thread instead of the main STA thread.
//
// Ultimately, it would be a very good idea to replace the 'getting shell object' logic
// to get a list of pidl's in 1 step, then look up their information in a 2nd, rather than
// looking them up as we get them. This would replace the need for the work around.
object padlock = new object();
lock (padlock)
{
IntPtr unknown = Marshal.GetIUnknownForObject(nativeShellItem2);
ThreadPool.QueueUserWorkItem(obj =>
{
lock (padlock)
{
pidl = ShellHelper.PidlFromUnknown(unknown);
new KnownFolderManagerClass().FindFolderFromIDList(pidl, out nativeFolder);
if (nativeFolder != null)
{
nativeFolder.GetFolderDefinition(out definition);
}
Monitor.Pulse(padlock);
}
});
Monitor.Wait(padlock);
}
return nativeFolder != null && definition.category == FolderCategory.Virtual;
}
finally
{
ShellNativeMethods.ILFree(pidl);
}
}
/// <summary>
/// Creates a ShellObject given a parsing name
/// </summary>
/// <param name="parsingName"></param>
/// <returns>A newly constructed ShellObject object</returns>
internal static ShellObject Create(string parsingName)
{
if (string.IsNullOrEmpty(parsingName))
{
throw new ArgumentNullException("parsingName");
}
// Create a native shellitem from our path
IShellItem2 nativeShellItem;
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
int retCode = ShellNativeMethods.SHCreateItemFromParsingName(parsingName, IntPtr.Zero, ref guid, out nativeShellItem);
if (!CoreErrorHelper.Succeeded(retCode))
{
throw new ShellException(LocalizedMessages.ShellObjectFactoryUnableToCreateItem, Marshal.GetExceptionForHR(retCode));
}
return ShellObjectFactory.Create(nativeShellItem);
}
/// <summary>
/// Constructs a new Shell object from IDList pointer
/// </summary>
/// <param name="idListPtr"></param>
/// <returns></returns>
internal static ShellObject Create(IntPtr idListPtr)
{
// Throw exception if not running on Win7 or newer.
CoreHelpers.ThrowIfNotVista();
Guid guid = new Guid(ShellIIDGuid.IShellItem2);
IShellItem2 nativeShellItem;
int retCode = ShellNativeMethods.SHCreateItemFromIDList(idListPtr, ref guid, out nativeShellItem);
if (!CoreErrorHelper.Succeeded(retCode)) { return null; }
return ShellObjectFactory.Create(nativeShellItem);
}
/// <summary>
/// Constructs a new Shell object from IDList pointer
/// </summary>
/// <param name="idListPtr"></param>
/// <param name="parent"></param>
/// <returns></returns>
internal static ShellObject Create(IntPtr idListPtr, ShellContainer parent)
{
IShellItem nativeShellItem;
int retCode = ShellNativeMethods.SHCreateShellItem(
IntPtr.Zero,
parent.NativeShellFolder,
idListPtr, out nativeShellItem);
if (!CoreErrorHelper.Succeeded(retCode)) { return null; }
return ShellObjectFactory.Create(nativeShellItem);
}
}
}

Просмотреть файл

@ -0,0 +1,18 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents a saved search
/// </summary>
public class ShellSavedSearchCollection : ShellSearchCollection
{
internal ShellSavedSearchCollection(IShellItem2 shellItem)
: base(shellItem)
{
CoreHelpers.ThrowIfNotVista();
}
}
}

Просмотреть файл

@ -0,0 +1,16 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// Represents the base class for all search-related classes.
/// </summary>
public class ShellSearchCollection : ShellContainer
{
internal ShellSearchCollection() { }
internal ShellSearchCollection(IShellItem2 shellItem) : base(shellItem) { }
}
}

Просмотреть файл

@ -0,0 +1,40 @@
//Copyright (c) Microsoft Corporation. All rights reserved.
using MS.WindowsAPICodePack.Internal;
namespace Microsoft.WindowsAPICodePack.Shell
{
/// <summary>
/// A Serch Connector folder in the Shell Namespace
/// </summary>
public sealed class ShellSearchConnector : ShellSearchCollection
{
#region Internal Constructor
internal ShellSearchConnector()
{
CoreHelpers.ThrowIfNotWin7();
}
internal ShellSearchConnector(IShellItem2 shellItem)
: this()
{
nativeShellItem = shellItem;
}
#endregion
/// <summary>
/// Indicates whether this feature is supported on the current platform.
/// </summary>
new public static bool IsPlatformSupported
{
get
{
// We need Windows 7 onwards ...
return CoreHelpers.RunningOnWin7;
}
}
}
}

Некоторые файлы не были показаны из-за слишком большого количества измененных файлов Показать больше