Code re-org

This commit is contained in:
Lorenz Cuno Klopfenstein 2018-04-10 18:52:40 +02:00
parent a152da4f2c
commit a7774b6677
220 changed files with 27071 additions and 28198 deletions

4
.gitignore vendored
View file

@ -1,8 +1,8 @@
.vs/* **/.vs/*
**/bin/* **/bin/*
**/obj/* **/obj/*
**/publish/* **/publish/*
Installer/OnTopReplica-Setup.exe Installer/OnTopReplica-Setup.exe
*.user *.user
*.suo *.suo
packages/ src/packages/*

Binary file not shown.

Binary file not shown.

File diff suppressed because it is too large Load diff

View file

@ -1,23 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<PublishUrlHistory>publish\</PublishUrlHistory>
<InstallUrlHistory>http://www.klopfenstein.net/public/Uploads/ontopreplica/|http://www.klopfenstein.net/download.aspx%3ffile=ontopreplica%252fsetup.exe/|http://www.klopfenstein.net/lorenz/programming/ontopreplica/|http://www.klopfenstein.net/lorenz/programming/|http://lorenz.klopfenstein.net/</InstallUrlHistory>
<SupportUrlHistory>http://www.klopfenstein.net/lorenz.aspx/ontopreplica|http://www.klopfenstein.net/loader.php%3fsection=lorenz&amp;page=on_top_replica|http://www.klopfenstein.net/loader.php%3fsection=lorenz&amp;page=programming_on_top_replica</SupportUrlHistory>
<UpdateUrlHistory>http://www.klopfenstein.net/public/Uploads/ontopreplica/|http://www.klopfenstein.net/lorenz/programming/ontopreplica/</UpdateUrlHistory>
<BootstrapperUrlHistory>
</BootstrapperUrlHistory>
<FallbackCulture>en-US</FallbackCulture>
<VerifyUploadedFiles>false</VerifyUploadedFiles>
<ErrorReportUrlHistory>
</ErrorReportUrlHistory>
<ProjectView>ProjectFiles</ProjectView>
</PropertyGroup>
<PropertyGroup>
<EnableSecurityDebugging>false</EnableSecurityDebugging>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|AnyCPU'">
<StartArguments>
</StartArguments>
</PropertyGroup>
</Project>

33
src/.editorconfig Normal file
View file

@ -0,0 +1,33 @@
root = true
[*]
insert_final_newline = true
trim_trailing_whitespace = true
[*.cs]
indent_style = space
indent_size = tab
tab_size = 4
dotnet_style_predefined_type_for_locals_parameters_members = true
dotnet_style_predefined_type_for_member_access = true
csharp_style_inlined_variable_declaration = true
csharp_style_conditional_delegate_call = true
csharp_prefer_braces = true
dotnet_sort_system_directives_first = true
csharp_new_line_before_open_brace = false
csharp_new_line_before_else = true
csharp_new_line_before_catch = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_object_initializers = false
csharp_indent_case_contents = true
csharp_indent_switch_labels = true
csharp_space_after_cast = false
csharp_space_after_keywords_in_control_flow_statements = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_preserve_single_line_blocks = true

View file

@ -1,55 +1,49 @@
 
Microsoft Visual Studio Solution File, Format Version 12.00 Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15 # Visual Studio 15
VisualStudioVersion = 15.0.27004.2008 VisualStudioVersion = 15.0.27004.2008
MinimumVisualStudioVersion = 10.0.40219.1 MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OnTopReplica", "OnTopReplica\OnTopReplica.csproj", "{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "OnTopReplica", "OnTopReplica\OnTopReplica.csproj", "{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}"
EndProject EndProject
Global Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64 Debug|x64 = Debug|x64
Debug|x86 = Debug|x86 Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64 Release|x64 = Release|x64
Release|x86 = Release|x86 Release|x86 = Release|x86
EndGlobalSection EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution GlobalSection(ProjectConfigurationPlatforms) = postSolution
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|Any CPU.Build.0 = Debug|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x64.ActiveCfg = Debug|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x64.ActiveCfg = Debug|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x64.Build.0 = Debug|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x64.Build.0 = Debug|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x86.ActiveCfg = Debug|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x86.ActiveCfg = Debug|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x86.Build.0 = Debug|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Debug|x86.Build.0 = Debug|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|Any CPU.ActiveCfg = Release|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|Any CPU.Build.0 = Release|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|Any CPU.Build.0 = Release|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x64.ActiveCfg = Release|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x64.ActiveCfg = Release|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x64.Build.0 = Release|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x64.Build.0 = Release|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x86.ActiveCfg = Release|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x86.ActiveCfg = Release|Any CPU
{E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x86.Build.0 = Release|Any CPU {E626BD6E-BF38-4EB7-A128-5CA6F40EF557}.Release|x86.Build.0 = Release|Any CPU
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Debug|Any CPU.ActiveCfg = Debug
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|Any CPU.Build.0 = Debug|Any CPU {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Debug|Any CPU.Build.0 = Debug
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|Any CPU.Deploy.0 = Debug|Any CPU {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Debug|x64.ActiveCfg = Debug
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|x64.ActiveCfg = Debug|x64 {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Debug|x64.Build.0 = Debug
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|x64.Build.0 = Debug|x64 {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Debug|x86.ActiveCfg = Debug
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|x64.Deploy.0 = Debug|x64 {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Debug|x86.Build.0 = Debug
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|x86.ActiveCfg = Debug|x86 {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Release|Any CPU.ActiveCfg = Release
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|x86.Build.0 = Debug|x86 {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Release|Any CPU.Build.0 = Release
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Debug|x86.Deploy.0 = Debug|x86 {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Release|x64.ActiveCfg = Release
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|Any CPU.ActiveCfg = Release|Any CPU {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Release|x64.Build.0 = Release
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|Any CPU.Build.0 = Release|Any CPU {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Release|x86.ActiveCfg = Release
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|Any CPU.Deploy.0 = Release|Any CPU {EA7C9C89-0CCF-41E3-A379-D593AAF7A941}.Release|x86.Build.0 = Release
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|x64.ActiveCfg = Release|x64 EndGlobalSection
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|x64.Build.0 = Release|x64 GlobalSection(SolutionProperties) = preSolution
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|x64.Deploy.0 = Release|x64 HideSolutionNode = FALSE
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|x86.ActiveCfg = Release|x86 EndGlobalSection
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|x86.Build.0 = Release|x86 GlobalSection(ExtensibilityGlobals) = postSolution
{01391A7F-A9A1-4C90-89EB-29E0C98BF9BE}.Release|x86.Deploy.0 = Release|x86 SolutionGuid = {3F135F78-F70E-4127-BA77-6C262C7CCCEF}
EndGlobalSection EndGlobalSection
GlobalSection(SolutionProperties) = preSolution EndGlobal
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3F135F78-F70E-4127-BA77-6C262C7CCCEF}
EndGlobalSection
EndGlobal

View file

@ -1,34 +1,34 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace OnTopReplica { namespace OnTopReplica {
public static class AppPaths { public static class AppPaths {
const string AppDataFolder = "OnTopReplica"; const string AppDataFolder = "OnTopReplica";
public static void SetupPaths() { public static void SetupPaths() {
var roamingAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); var roamingAppData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
var roamingAppDataApplicationPath = Path.Combine(roamingAppData, AppDataFolder); var roamingAppDataApplicationPath = Path.Combine(roamingAppData, AppDataFolder);
if (!Directory.Exists(roamingAppDataApplicationPath)) { if (!Directory.Exists(roamingAppDataApplicationPath)) {
Directory.CreateDirectory(roamingAppDataApplicationPath); Directory.CreateDirectory(roamingAppDataApplicationPath);
} }
PrivateRoamingFolderPath = roamingAppDataApplicationPath; PrivateRoamingFolderPath = roamingAppDataApplicationPath;
} }
public static string PrivateRoamingFolderPath { get; private set; } public static string PrivateRoamingFolderPath { get; private set; }
public static string GenerateCrashDumpPath() { public static string GenerateCrashDumpPath() {
var now = DateTime.Now; var now = DateTime.Now;
string dump = string.Format("OnTopReplica-dump-{0}{1}{2}-{3}{4}.txt", string dump = string.Format("OnTopReplica-dump-{0}{1}{2}-{3}{4}.txt",
now.Year, now.Month, now.Day, now.Year, now.Month, now.Day,
now.Hour, now.Minute); now.Hour, now.Minute);
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), dump); return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), dump);
} }
} }
} }

View file

@ -1,135 +1,135 @@
<?xml version="1.0" encoding="utf-8"?> <?xml version="1.0" encoding="utf-8"?>
<root> <root>
<!-- <!--
Microsoft ResX Schema Microsoft ResX Schema
Version 2.0 Version 2.0
The primary goals of this format is to allow a simple XML format The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes various data types are done through the TypeConverter classes
associated with the data types. associated with the data types.
Example: Example:
... ado.net/XML headers & schema ... ... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader> <resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader> <resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader> <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, 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="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="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64"> <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value> <value>[base64 mime encoded serialized .NET Framework object]</value>
</data> </data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64"> <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> <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment> <comment>This is a comment</comment>
</data> </data>
There are any number of "resheader" rows that contain simple There are any number of "resheader" rows that contain simple
name/value pairs. name/value pairs.
Each data row contains a name, and value. The row also contains a Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture. text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the Classes that don't support this are serialized and stored with the
mimetype set. mimetype set.
The mimetype is used for serialized objects, and tells the The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly: extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below. read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64 mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64 mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding. : and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64 mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter : using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding. : 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: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:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true"> <xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType> <xsd:complexType>
<xsd:choice maxOccurs="unbounded"> <xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata"> <xsd:element name="metadata">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" /> <xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" /> <xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" /> <xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" /> <xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" /> <xsd:attribute ref="xml:space" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="assembly"> <xsd:element name="assembly">
<xsd:complexType> <xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" /> <xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" /> <xsd:attribute name="name" type="xsd:string" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="data"> <xsd:element name="data">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <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:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" /> <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="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" /> <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" /> <xsd:attribute ref="xml:space" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
<xsd:element name="resheader"> <xsd:element name="resheader">
<xsd:complexType> <xsd:complexType>
<xsd:sequence> <xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" /> <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence> </xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" /> <xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xsd:choice> </xsd:choice>
</xsd:complexType> </xsd:complexType>
</xsd:element> </xsd:element>
</xsd:schema> </xsd:schema>
<resheader name="resmimetype"> <resheader name="resmimetype">
<value>text/microsoft-resx</value> <value>text/microsoft-resx</value>
</resheader> </resheader>
<resheader name="version"> <resheader name="version">
<value>2.0</value> <value>2.0</value>
</resheader> </resheader>
<resheader name="reader"> <resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<resheader name="writer"> <resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value> <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader> </resheader>
<data name="ApplicationWebsite" xml:space="preserve"> <data name="ApplicationWebsite" xml:space="preserve">
<value>http://ontopreplica.codeplex.com</value> <value>http://ontopreplica.codeplex.com</value>
</data> </data>
<data name="AuthorWebsite" xml:space="preserve"> <data name="AuthorWebsite" xml:space="preserve">
<value>http://lorenz.klopfenstein.net</value> <value>http://lorenz.klopfenstein.net</value>
</data> </data>
<data name="LatestCommitsLink" xml:space="preserve"> <data name="LatestCommitsLink" xml:space="preserve">
<value>http://ontopreplica.codeplex.com/SourceControl/list/changesets</value> <value>http://ontopreplica.codeplex.com/SourceControl/list/changesets</value>
</data> </data>
<data name="MsRlLicenseLink" xml:space="preserve"> <data name="MsRlLicenseLink" xml:space="preserve">
<value>http://opensource.org/licenses/ms-rl.html</value> <value>http://opensource.org/licenses/ms-rl.html</value>
</data> </data>
<data name="UpdateFeed" xml:space="preserve"> <data name="UpdateFeed" xml:space="preserve">
<value>http://ontopreplica.codeplex.com/project/feeds/rss?ProjectRSSFeed=codeplex%3a%2f%2frelease%2fontopreplica</value> <value>http://ontopreplica.codeplex.com/project/feeds/rss?ProjectRSSFeed=codeplex%3a%2f%2frelease%2fontopreplica</value>
</data> </data>
</root> </root>

View file

@ -1,266 +1,266 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Native; using OnTopReplica.Native;
namespace OnTopReplica { namespace OnTopReplica {
/// <summary> /// <summary>
/// Form that automatically keeps a certain aspect ratio and resizes without flickering. /// Form that automatically keeps a certain aspect ratio and resizes without flickering.
/// </summary> /// </summary>
public class AspectRatioForm : WindowsFormsAero.AeroForm { public class AspectRatioForm : WindowsFormsAero.AeroForm {
bool _keepAspectRatio = true; bool _keepAspectRatio = true;
/// <summary> /// <summary>
/// Gets or sets whether the form should keep its aspect ratio. /// Gets or sets whether the form should keep its aspect ratio.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Refreshes the window's size if set to true. /// Refreshes the window's size if set to true.
/// </remarks> /// </remarks>
[Description("Enables fixed aspect ratio for this form."), Category("Appearance"), DefaultValue(true)] [Description("Enables fixed aspect ratio for this form."), Category("Appearance"), DefaultValue(true)]
public bool KeepAspectRatio { public bool KeepAspectRatio {
get { get {
return _keepAspectRatio; return _keepAspectRatio;
} }
set { set {
_keepAspectRatio = value; _keepAspectRatio = value;
if (value) if (value)
RefreshAspectRatio(); RefreshAspectRatio();
} }
} }
double _aspectRatio = 1.0; double _aspectRatio = 1.0;
/// <summary> /// <summary>
/// Gets or sets the form's aspect ratio that will be kept automatically when resizing. /// Gets or sets the form's aspect ratio that will be kept automatically when resizing.
/// </summary> /// </summary>
[Description("Determines this form's fixed aspect ratio."), Category("Appearance"), DefaultValue(1.0)] [Description("Determines this form's fixed aspect ratio."), Category("Appearance"), DefaultValue(1.0)]
public double AspectRatio { public double AspectRatio {
get { get {
return _aspectRatio; return _aspectRatio;
} }
set { set {
if (value <= 0.0 || Double.IsInfinity(value)) if (value <= 0.0 || Double.IsInfinity(value))
return; return;
_aspectRatio = value; _aspectRatio = value;
} }
} }
Padding _extraPadding; Padding _extraPadding;
/// <summary> /// <summary>
/// Gets or sets some additional internal padding of the form that is ignored when keeping the aspect ratio. /// Gets or sets some additional internal padding of the form that is ignored when keeping the aspect ratio.
/// </summary> /// </summary>
[Description("Sets some padding inside the form's client area that is ignored when keeping the aspect ratio."), [Description("Sets some padding inside the form's client area that is ignored when keeping the aspect ratio."),
Category("Appearance")] Category("Appearance")]
public Padding ExtraPadding { public Padding ExtraPadding {
get { get {
return _extraPadding; return _extraPadding;
} }
set { set {
_extraPadding = value; _extraPadding = value;
if(KeepAspectRatio) if(KeepAspectRatio)
RefreshAspectRatio(); RefreshAspectRatio();
} }
} }
/// <summary> /// <summary>
/// Forces the form to update its height based on the current aspect ratio setting. /// Forces the form to update its height based on the current aspect ratio setting.
/// </summary> /// </summary>
public void RefreshAspectRatio() { public void RefreshAspectRatio() {
int newWidth = ClientSize.Width; int newWidth = ClientSize.Width;
int newHeight = (int)((ClientSize.Width - ExtraPadding.Horizontal) / AspectRatio) + ExtraPadding.Vertical; int newHeight = (int)((ClientSize.Width - ExtraPadding.Horizontal) / AspectRatio) + ExtraPadding.Vertical;
//Adapt height if it doesn't respect the form's minimum size //Adapt height if it doesn't respect the form's minimum size
Size clientMinimumSize = FromSizeToClientSize(MinimumSize); Size clientMinimumSize = FromSizeToClientSize(MinimumSize);
if (newHeight < clientMinimumSize.Height) { if (newHeight < clientMinimumSize.Height) {
newHeight = clientMinimumSize.Height; newHeight = clientMinimumSize.Height;
newWidth = (int)((newHeight - ExtraPadding.Vertical) * AspectRatio) + ExtraPadding.Horizontal; newWidth = (int)((newHeight - ExtraPadding.Vertical) * AspectRatio) + ExtraPadding.Horizontal;
} }
//Adapt height if it exceeds the screen's height //Adapt height if it exceeds the screen's height
var workingArea = Screen.GetWorkingArea(this); var workingArea = Screen.GetWorkingArea(this);
if (newHeight >= workingArea.Height) { if (newHeight >= workingArea.Height) {
newHeight = workingArea.Height; newHeight = workingArea.Height;
newWidth = (int)((newHeight - ExtraPadding.Vertical) * AspectRatio) + ExtraPadding.Horizontal; newWidth = (int)((newHeight - ExtraPadding.Vertical) * AspectRatio) + ExtraPadding.Horizontal;
} }
//Update size //Update size
ClientSize = new Size(newWidth, newHeight); ClientSize = new Size(newWidth, newHeight);
//Move form vertically to adapt to new size //Move form vertically to adapt to new size
//REMOVED: allows the window to correctly be restored slightly off screen //REMOVED: allows the window to correctly be restored slightly off screen
/*if (Location.Y + Size.Height > workingArea.Y + workingArea.Height) { /*if (Location.Y + Size.Height > workingArea.Y + workingArea.Height) {
int offsetY = (workingArea.Y + workingArea.Height) - (Location.Y + Size.Height); int offsetY = (workingArea.Y + workingArea.Height) - (Location.Y + Size.Height);
Location = new Point(Location.X, Location.Y - offsetY); Location = new Point(Location.X, Location.Y - offsetY);
}*/ }*/
} }
/// <summary> /// <summary>
/// Adjusts the size of the form by a pixel increment while keeping its aspect ratio. /// Adjusts the size of the form by a pixel increment while keeping its aspect ratio.
/// </summary> /// </summary>
/// <param name="pixelIncrement">Change of size in pixels.</param> /// <param name="pixelIncrement">Change of size in pixels.</param>
public void AdjustSize(int pixelOffset) { public void AdjustSize(int pixelOffset) {
Size origSize = Size; Size origSize = Size;
//Resize to new width (clamped to max allowed size and minimum form size) //Resize to new width (clamped to max allowed size and minimum form size)
int newWidth = Math.Max(Math.Min(origSize.Width + pixelOffset, int newWidth = Math.Max(Math.Min(origSize.Width + pixelOffset,
SystemInformation.MaxWindowTrackSize.Width), SystemInformation.MaxWindowTrackSize.Width),
MinimumSize.Width); MinimumSize.Width);
//Determine new height while keeping aspect ratio //Determine new height while keeping aspect ratio
var clientConversionDifference = ClientWindowDifference; var clientConversionDifference = ClientWindowDifference;
int newHeight = (int)((newWidth - ExtraPadding.Horizontal - clientConversionDifference.Width) / AspectRatio) + ExtraPadding.Vertical + clientConversionDifference.Height; int newHeight = (int)((newWidth - ExtraPadding.Horizontal - clientConversionDifference.Width) / AspectRatio) + ExtraPadding.Vertical + clientConversionDifference.Height;
//Apply and move form to recenter //Apply and move form to recenter
Size = new Size(newWidth, newHeight); Size = new Size(newWidth, newHeight);
int deltaX = Size.Width - origSize.Width; int deltaX = Size.Width - origSize.Width;
int deltaY = Size.Height - origSize.Height; int deltaY = Size.Height - origSize.Height;
Location = new System.Drawing.Point(Location.X - (deltaX / 2), Location.Y - (deltaY / 2)); Location = new System.Drawing.Point(Location.X - (deltaX / 2), Location.Y - (deltaY / 2));
} }
/// <summary> /// <summary>
/// Updates the aspect ratio of the form and optionally forces a refresh. /// Updates the aspect ratio of the form and optionally forces a refresh.
/// </summary> /// </summary>
/// <param name="aspectRatioSource">Size from which aspect ratio should be computed.</param> /// <param name="aspectRatioSource">Size from which aspect ratio should be computed.</param>
/// <param name="forceRefresh">True if the size of the form should be refreshed to match the new aspect ratio.</param> /// <param name="forceRefresh">True if the size of the form should be refreshed to match the new aspect ratio.</param>
public void SetAspectRatio(Size aspectRatioSource, bool forceRefresh) { public void SetAspectRatio(Size aspectRatioSource, bool forceRefresh) {
AspectRatio = ((double)aspectRatioSource.Width / (double)aspectRatioSource.Height); AspectRatio = ((double)aspectRatioSource.Width / (double)aspectRatioSource.Height);
_keepAspectRatio = true; _keepAspectRatio = true;
//Log.Write("Setting new aspect ratio {0} (for {1})", AspectRatio, aspectRatioSource); //Log.Write("Setting new aspect ratio {0} (for {1})", AspectRatio, aspectRatioSource);
if (forceRefresh) { if (forceRefresh) {
RefreshAspectRatio(); RefreshAspectRatio();
} }
} }
#region Event overriding #region Event overriding
protected override void OnResizeEnd(EventArgs e) { protected override void OnResizeEnd(EventArgs e) {
base.OnResizeEnd(e); base.OnResizeEnd(e);
//Ensure that the ClientSize of the form is always respected //Ensure that the ClientSize of the form is always respected
//(not ensured by the WM_SIZING message alone because of rounding errors and the chrome space) //(not ensured by the WM_SIZING message alone because of rounding errors and the chrome space)
if (KeepAspectRatio) { if (KeepAspectRatio) {
var newHeight = ComputeHeightFromWidth(ClientSize.Width); var newHeight = ComputeHeightFromWidth(ClientSize.Width);
ClientSize = new Size(ClientSize.Width, newHeight); ClientSize = new Size(ClientSize.Width, newHeight);
} }
} }
protected virtual void OnResizing(EventArgs e) { protected virtual void OnResizing(EventArgs e) {
} }
/// <summary> /// <summary>
/// Override WM_SIZING message to restrict resizing. /// Override WM_SIZING message to restrict resizing.
/// Taken from: http://www.vcskicks.com/maintain-aspect-ratio.php /// Taken from: http://www.vcskicks.com/maintain-aspect-ratio.php
/// Improved with code from: http://stoyanoff.info/blog/2010/06/27/resizing-forms-while-keeping-aspect-ratio/ /// Improved with code from: http://stoyanoff.info/blog/2010/06/27/resizing-forms-while-keeping-aspect-ratio/
/// </summary> /// </summary>
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
if (m.Msg == WM.SIZING) { if (m.Msg == WM.SIZING) {
this.OnResizing(EventArgs.Empty); this.OnResizing(EventArgs.Empty);
if (KeepAspectRatio) { if (KeepAspectRatio) {
var clientSizeConversion = ClientWindowDifference; var clientSizeConversion = ClientWindowDifference;
var rc = (Native.NRectangle)Marshal.PtrToStructure(m.LParam, typeof(Native.NRectangle)); var rc = (Native.NRectangle)Marshal.PtrToStructure(m.LParam, typeof(Native.NRectangle));
int res = m.WParam.ToInt32(); int res = m.WParam.ToInt32();
int width = (rc.Right - rc.Left) - clientSizeConversion.Width - ExtraPadding.Horizontal; int width = (rc.Right - rc.Left) - clientSizeConversion.Width - ExtraPadding.Horizontal;
int height = (rc.Bottom - rc.Top) - clientSizeConversion.Height - ExtraPadding.Vertical; int height = (rc.Bottom - rc.Top) - clientSizeConversion.Height - ExtraPadding.Vertical;
if (res == WMSZ.LEFT || res == WMSZ.RIGHT) { if (res == WMSZ.LEFT || res == WMSZ.RIGHT) {
//Left or right resize, adjust top and bottom //Left or right resize, adjust top and bottom
int targetHeight = (int)(width / AspectRatio); int targetHeight = (int)(width / AspectRatio);
int diffHeight = height - targetHeight; int diffHeight = height - targetHeight;
rc.Top += (int)(diffHeight / 2.0); rc.Top += (int)(diffHeight / 2.0);
rc.Bottom = rc.Top + targetHeight + ExtraPadding.Vertical + clientSizeConversion.Height; rc.Bottom = rc.Top + targetHeight + ExtraPadding.Vertical + clientSizeConversion.Height;
} }
else if (res == WMSZ.TOP || res == WMSZ.BOTTOM) { else if (res == WMSZ.TOP || res == WMSZ.BOTTOM) {
//Up or down resize, adjust left and right //Up or down resize, adjust left and right
int targetWidth = (int)(height * AspectRatio); int targetWidth = (int)(height * AspectRatio);
int diffWidth = width - targetWidth; int diffWidth = width - targetWidth;
rc.Left += (int)(diffWidth / 2.0); rc.Left += (int)(diffWidth / 2.0);
rc.Right = rc.Left + targetWidth + ExtraPadding.Horizontal + clientSizeConversion.Width; rc.Right = rc.Left + targetWidth + ExtraPadding.Horizontal + clientSizeConversion.Width;
} }
else if (res == WMSZ.RIGHT + WMSZ.BOTTOM || res == WMSZ.LEFT + WMSZ.BOTTOM) { else if (res == WMSZ.RIGHT + WMSZ.BOTTOM || res == WMSZ.LEFT + WMSZ.BOTTOM) {
//Lower corner resize, adjust bottom //Lower corner resize, adjust bottom
rc.Bottom = rc.Top + (int)(width / AspectRatio) + ExtraPadding.Vertical + clientSizeConversion.Height; rc.Bottom = rc.Top + (int)(width / AspectRatio) + ExtraPadding.Vertical + clientSizeConversion.Height;
} }
else if (res == WMSZ.LEFT + WMSZ.TOP || res == WMSZ.RIGHT + WMSZ.TOP) { else if (res == WMSZ.LEFT + WMSZ.TOP || res == WMSZ.RIGHT + WMSZ.TOP) {
//Upper corner resize, adjust top //Upper corner resize, adjust top
rc.Top = rc.Bottom - (int)(width / AspectRatio) - ExtraPadding.Vertical - clientSizeConversion.Height; rc.Top = rc.Bottom - (int)(width / AspectRatio) - ExtraPadding.Vertical - clientSizeConversion.Height;
} }
Marshal.StructureToPtr(rc, m.LParam, false); Marshal.StructureToPtr(rc, m.LParam, false);
} }
} }
base.WndProc(ref m); base.WndProc(ref m);
} }
#endregion #endregion
#region Conversion helpers #region Conversion helpers
/// <summary> /// <summary>
/// Converts a client size measurement to a window size measurement. /// Converts a client size measurement to a window size measurement.
/// </summary> /// </summary>
/// <param name="clientSize">Size of the window's client area.</param> /// <param name="clientSize">Size of the window's client area.</param>
/// <returns>Size of the whole window.</returns> /// <returns>Size of the whole window.</returns>
public Size FromClientSizeToSize(Size clientSize) { public Size FromClientSizeToSize(Size clientSize) {
var difference = ClientWindowDifference; var difference = ClientWindowDifference;
return new Size(clientSize.Width + difference.Width, clientSize.Height + difference.Height); return new Size(clientSize.Width + difference.Width, clientSize.Height + difference.Height);
} }
/// <summary> /// <summary>
/// Converts a window size measurement to a client size measurement. /// Converts a window size measurement to a client size measurement.
/// </summary> /// </summary>
/// <param name="size">Size of the whole window.</param> /// <param name="size">Size of the whole window.</param>
/// <returns>Size of the window's client area.</returns> /// <returns>Size of the window's client area.</returns>
public Size FromSizeToClientSize(Size size) { public Size FromSizeToClientSize(Size size) {
var difference = ClientWindowDifference; var difference = ClientWindowDifference;
return new Size(size.Width - difference.Width, size.Height - difference.Height); return new Size(size.Width - difference.Width, size.Height - difference.Height);
} }
/// <summary> /// <summary>
/// Computes height from width value, according to aspect ratio of window. /// Computes height from width value, according to aspect ratio of window.
/// </summary> /// </summary>
public int ComputeHeightFromWidth(int width) { public int ComputeHeightFromWidth(int width) {
return (int)Math.Round(((width - ExtraPadding.Horizontal) / AspectRatio) + ExtraPadding.Vertical); return (int)Math.Round(((width - ExtraPadding.Horizontal) / AspectRatio) + ExtraPadding.Vertical);
} }
/// <summary> /// <summary>
/// Computes width from height value, according to aspect ratio of window. /// Computes width from height value, according to aspect ratio of window.
/// </summary> /// </summary>
public int ComputeWidthFromHeight(int height) { public int ComputeWidthFromHeight(int height) {
return (int)Math.Round(((height - ExtraPadding.Vertical) * AspectRatio) + ExtraPadding.Horizontal); return (int)Math.Round(((height - ExtraPadding.Vertical) * AspectRatio) + ExtraPadding.Horizontal);
} }
#endregion #endregion
/// <summary> /// <summary>
/// Gets the difference in pixels between a client size value and a window size value (depending on window decoration). /// Gets the difference in pixels between a client size value and a window size value (depending on window decoration).
/// </summary> /// </summary>
protected Size ClientWindowDifference { protected Size ClientWindowDifference {
get { get {
long style = WindowMethods.GetWindowLong(this.Handle, WindowMethods.WindowLong.Style).ToInt64(); long style = WindowMethods.GetWindowLong(this.Handle, WindowMethods.WindowLong.Style).ToInt64();
long exStyle = WindowMethods.GetWindowLong(this.Handle, WindowMethods.WindowLong.ExStyle).ToInt64(); long exStyle = WindowMethods.GetWindowLong(this.Handle, WindowMethods.WindowLong.ExStyle).ToInt64();
return WindowMethods.ConvertClientToWindowRect(new NRectangle(0, 0, 0, 0), style, exStyle).Size; return WindowMethods.ConvertClientToWindowRect(new NRectangle(0, 0, 0, 0), style, exStyle).Size;
} }
} }
} }
} }

View file

Before

Width:  |  Height:  |  Size: 639 B

After

Width:  |  Height:  |  Size: 639 B

View file

Before

Width:  |  Height:  |  Size: 218 B

After

Width:  |  Height:  |  Size: 218 B

View file

Before

Width:  |  Height:  |  Size: 209 B

After

Width:  |  Height:  |  Size: 209 B

View file

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 147 KiB

View file

Before

Width:  |  Height:  |  Size: 951 B

After

Width:  |  Height:  |  Size: 951 B

View file

Before

Width:  |  Height:  |  Size: 731 B

After

Width:  |  Height:  |  Size: 731 B

View file

Before

Width:  |  Height:  |  Size: 794 B

After

Width:  |  Height:  |  Size: 794 B

View file

Before

Width:  |  Height:  |  Size: 11 KiB

After

Width:  |  Height:  |  Size: 11 KiB

View file

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 15 KiB

View file

Before

Width:  |  Height:  |  Size: 241 B

After

Width:  |  Height:  |  Size: 241 B

View file

Before

Width:  |  Height:  |  Size: 347 B

After

Width:  |  Height:  |  Size: 347 B

View file

Before

Width:  |  Height:  |  Size: 202 B

After

Width:  |  Height:  |  Size: 202 B

View file

Before

Width:  |  Height:  |  Size: 209 B

After

Width:  |  Height:  |  Size: 209 B

View file

Before

Width:  |  Height:  |  Size: 183 B

After

Width:  |  Height:  |  Size: 183 B

View file

Before

Width:  |  Height:  |  Size: 300 B

After

Width:  |  Height:  |  Size: 300 B

View file

Before

Width:  |  Height:  |  Size: 205 B

After

Width:  |  Height:  |  Size: 205 B

View file

Before

Width:  |  Height:  |  Size: 355 B

After

Width:  |  Height:  |  Size: 355 B

View file

Before

Width:  |  Height:  |  Size: 396 B

After

Width:  |  Height:  |  Size: 396 B

View file

Before

Width:  |  Height:  |  Size: 837 B

After

Width:  |  Height:  |  Size: 837 B

View file

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

View file

Before

Width:  |  Height:  |  Size: 85 KiB

After

Width:  |  Height:  |  Size: 85 KiB

View file

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

View file

Before

Width:  |  Height:  |  Size: 7.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

View file

Before

Width:  |  Height:  |  Size: 681 B

After

Width:  |  Height:  |  Size: 681 B

View file

Before

Width:  |  Height:  |  Size: 770 B

After

Width:  |  Height:  |  Size: 770 B

View file

Before

Width:  |  Height:  |  Size: 267 B

After

Width:  |  Height:  |  Size: 267 B

View file

Before

Width:  |  Height:  |  Size: 267 B

After

Width:  |  Height:  |  Size: 267 B

View file

Before

Width:  |  Height:  |  Size: 231 B

After

Width:  |  Height:  |  Size: 231 B

View file

Before

Width:  |  Height:  |  Size: 250 B

After

Width:  |  Height:  |  Size: 250 B

View file

Before

Width:  |  Height:  |  Size: 280 B

After

Width:  |  Height:  |  Size: 280 B

View file

Before

Width:  |  Height:  |  Size: 278 B

After

Width:  |  Height:  |  Size: 278 B

View file

Before

Width:  |  Height:  |  Size: 259 B

After

Width:  |  Height:  |  Size: 259 B

View file

Before

Width:  |  Height:  |  Size: 296 B

After

Width:  |  Height:  |  Size: 296 B

View file

Before

Width:  |  Height:  |  Size: 207 B

After

Width:  |  Height:  |  Size: 207 B

View file

Before

Width:  |  Height:  |  Size: 97 KiB

After

Width:  |  Height:  |  Size: 97 KiB

View file

Before

Width:  |  Height:  |  Size: 862 B

After

Width:  |  Height:  |  Size: 862 B

View file

Before

Width:  |  Height:  |  Size: 683 B

After

Width:  |  Height:  |  Size: 683 B

View file

Before

Width:  |  Height:  |  Size: 894 B

After

Width:  |  Height:  |  Size: 894 B

View file

Before

Width:  |  Height:  |  Size: 1,012 B

After

Width:  |  Height:  |  Size: 1,012 B

View file

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View file

Before

Width:  |  Height:  |  Size: 894 B

After

Width:  |  Height:  |  Size: 894 B

View file

Before

Width:  |  Height:  |  Size: 810 B

After

Width:  |  Height:  |  Size: 810 B

View file

Before

Width:  |  Height:  |  Size: 456 B

After

Width:  |  Height:  |  Size: 456 B

View file

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View file

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 3.4 KiB

View file

Before

Width:  |  Height:  |  Size: 753 B

After

Width:  |  Height:  |  Size: 753 B

View file

Before

Width:  |  Height:  |  Size: 437 B

After

Width:  |  Height:  |  Size: 437 B

View file

Before

Width:  |  Height:  |  Size: 715 B

After

Width:  |  Height:  |  Size: 715 B

View file

Before

Width:  |  Height:  |  Size: 761 B

After

Width:  |  Height:  |  Size: 761 B

View file

Before

Width:  |  Height:  |  Size: 752 B

After

Width:  |  Height:  |  Size: 752 B

View file

Before

Width:  |  Height:  |  Size: 752 B

After

Width:  |  Height:  |  Size: 752 B

View file

Before

Width:  |  Height:  |  Size: 744 B

After

Width:  |  Height:  |  Size: 744 B

View file

Before

Width:  |  Height:  |  Size: 459 B

After

Width:  |  Height:  |  Size: 459 B

View file

@ -1,17 +1,17 @@
OnTopReplica credits OnTopReplica credits
-------------------- --------------------
This application was inspired by Switcher (http://insentient.net) and other This application was inspired by Switcher (http://insentient.net) and other
DWM based application. DWM based application.
All Aero controls are part of the open-source WindowsFormsAero All Aero controls are part of the open-source WindowsFormsAero
(http://windowsformsaero.codeplex.com) library for .NET. (http://windowsformsaero.codeplex.com) library for .NET.
Some DWM example code has ben taken from user Ookii (http://www.ookii.org) on Some DWM example code has ben taken from user Ookii (http://www.ookii.org) on
Channel 9 MSDN. Channel 9 MSDN.
The NativeToolstripRenderer class has been taken from asztal.net The NativeToolstripRenderer class has been taken from asztal.net
(http://wp.asztal.net/2007/12/vista-style-menus-in-dotnet). (http://wp.asztal.net/2007/12/vista-style-menus-in-dotnet).
Some of the icons used by OnTopReplica have been taken from VistaICO.com and Some of the icons used by OnTopReplica have been taken from VistaICO.com and
the Xiao icon set. the Xiao icon set.

View file

@ -1,32 +1,32 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica { namespace OnTopReplica {
/// <summary> /// <summary>
/// EventArgs structure for clicks on a cloned window. /// EventArgs structure for clicks on a cloned window.
/// </summary> /// </summary>
public class CloneClickEventArgs : EventArgs { public class CloneClickEventArgs : EventArgs {
public Point ClientClickLocation { get; set; } public Point ClientClickLocation { get; set; }
public bool IsDoubleClick { get; set; } public bool IsDoubleClick { get; set; }
public MouseButtons Buttons { get; set; } public MouseButtons Buttons { get; set; }
public CloneClickEventArgs(Point location, MouseButtons buttons) { public CloneClickEventArgs(Point location, MouseButtons buttons) {
ClientClickLocation = location; ClientClickLocation = location;
Buttons = buttons; Buttons = buttons;
IsDoubleClick = false; IsDoubleClick = false;
} }
public CloneClickEventArgs(Point location, MouseButtons buttons, bool doubleClick) { public CloneClickEventArgs(Point location, MouseButtons buttons, bool doubleClick) {
ClientClickLocation = location; ClientClickLocation = location;
Buttons = buttons; Buttons = buttons;
IsDoubleClick = doubleClick; IsDoubleClick = doubleClick;
} }
} }
} }

View file

@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Drawing; using System.Drawing;
namespace OnTopReplica { namespace OnTopReplica {
public class CloseRequestEventArgs : EventArgs { public class CloseRequestEventArgs : EventArgs {
public WindowHandle LastWindowHandle { get; set; } public WindowHandle LastWindowHandle { get; set; }
public Rectangle? LastRegion { get; set; } public Rectangle? LastRegion { get; set; }
} }
} }

View file

@ -1,68 +1,68 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using WindowsFormsAero; using WindowsFormsAero;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica { namespace OnTopReplica {
class FocusedTextBox : System.Windows.Forms.TextBox { class FocusedTextBox : System.Windows.Forms.TextBox {
protected override bool IsInputChar(char charCode) { protected override bool IsInputChar(char charCode) {
if (charCode == '\n' || charCode == '\r') if (charCode == '\n' || charCode == '\r')
return true; return true;
return base.IsInputChar(charCode); return base.IsInputChar(charCode);
} }
protected override void OnKeyUp(KeyEventArgs e) { protected override void OnKeyUp(KeyEventArgs e) {
if (e.KeyCode == Keys.Return) { if (e.KeyCode == Keys.Return) {
if(!string.IsNullOrEmpty(Text)) if(!string.IsNullOrEmpty(Text))
OnConfirmInput(); OnConfirmInput();
e.Handled = true; e.Handled = true;
e.SuppressKeyPress = true; e.SuppressKeyPress = true;
} }
else if (e.KeyCode == Keys.Escape) { else if (e.KeyCode == Keys.Escape) {
OnAbortInput(); OnAbortInput();
e.Handled = true; e.Handled = true;
e.SuppressKeyPress = true; e.SuppressKeyPress = true;
} }
base.OnKeyUp(e); base.OnKeyUp(e);
} }
//List of characters to ignore on KeyPress events (because they generate bell rings) //List of characters to ignore on KeyPress events (because they generate bell rings)
readonly char[] IgnoreChars = new char[] { readonly char[] IgnoreChars = new char[] {
(char)27, (char)13 (char)27, (char)13
}; };
protected override void OnKeyPress(KeyPressEventArgs e) { protected override void OnKeyPress(KeyPressEventArgs e) {
if (IgnoreChars.Contains(e.KeyChar)) { if (IgnoreChars.Contains(e.KeyChar)) {
e.Handled = true; e.Handled = true;
} }
base.OnKeyPress(e); base.OnKeyPress(e);
} }
public event EventHandler ConfirmInput; public event EventHandler ConfirmInput;
protected virtual void OnConfirmInput() { protected virtual void OnConfirmInput() {
var evt = ConfirmInput; var evt = ConfirmInput;
if (evt != null) if (evt != null)
evt(this, EventArgs.Empty); evt(this, EventArgs.Empty);
} }
public event EventHandler AbortInput; public event EventHandler AbortInput;
protected virtual void OnAbortInput() { protected virtual void OnAbortInput() {
var evt = AbortInput; var evt = AbortInput;
if (evt != null) if (evt != null)
evt(this, EventArgs.Empty); evt(this, EventArgs.Empty);
} }
} }
} }

View file

@ -1,116 +1,116 @@
using OnTopReplica.Properties; using OnTopReplica.Properties;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Drawing; using System.Drawing;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica { namespace OnTopReplica {
class FullscreenFormManager { class FullscreenFormManager {
private readonly MainForm _mainForm; private readonly MainForm _mainForm;
public FullscreenFormManager(MainForm form) { public FullscreenFormManager(MainForm form) {
_mainForm = form; _mainForm = form;
IsFullscreen = false; IsFullscreen = false;
} }
Point _preFullscreenLocation; Point _preFullscreenLocation;
Size _preFullscreenSize; Size _preFullscreenSize;
FormBorderStyle _preFullscreenBorderStyle; FormBorderStyle _preFullscreenBorderStyle;
public bool IsFullscreen { public bool IsFullscreen {
get; get;
private set; private set;
} }
public void SwitchFullscreen() { public void SwitchFullscreen() {
SwitchFullscreen(Settings.Default.GetFullscreenMode()); SwitchFullscreen(Settings.Default.GetFullscreenMode());
} }
public void SwitchFullscreen(FullscreenMode mode) { public void SwitchFullscreen(FullscreenMode mode) {
if (IsFullscreen) { if (IsFullscreen) {
MoveToFullscreenMode(mode); MoveToFullscreenMode(mode);
return; return;
} }
if (!_mainForm.ThumbnailPanel.IsShowingThumbnail) if (!_mainForm.ThumbnailPanel.IsShowingThumbnail)
return; return;
//On switch, always hide side panels //On switch, always hide side panels
_mainForm.CloseSidePanel(); _mainForm.CloseSidePanel();
//Store state //Store state
_preFullscreenLocation = _mainForm.Location; _preFullscreenLocation = _mainForm.Location;
_preFullscreenSize = _mainForm.ClientSize; _preFullscreenSize = _mainForm.ClientSize;
_preFullscreenBorderStyle = _mainForm.FormBorderStyle; _preFullscreenBorderStyle = _mainForm.FormBorderStyle;
//Change state to fullscreen //Change state to fullscreen
_mainForm.FormBorderStyle = FormBorderStyle.None; _mainForm.FormBorderStyle = FormBorderStyle.None;
MoveToFullscreenMode(mode); MoveToFullscreenMode(mode);
CommonCompleteSwitch(true); CommonCompleteSwitch(true);
} }
private void MoveToFullscreenMode(FullscreenMode mode) { private void MoveToFullscreenMode(FullscreenMode mode) {
var screens = Screen.AllScreens; var screens = Screen.AllScreens;
var currentScreen = Screen.FromControl(_mainForm); var currentScreen = Screen.FromControl(_mainForm);
Size size = _mainForm.Size; Size size = _mainForm.Size;
Point location = _mainForm.Location; Point location = _mainForm.Location;
switch (mode) { switch (mode) {
case FullscreenMode.Standard: case FullscreenMode.Standard:
default: default:
size = currentScreen.WorkingArea.Size; size = currentScreen.WorkingArea.Size;
location = currentScreen.WorkingArea.Location; location = currentScreen.WorkingArea.Location;
break; break;
case FullscreenMode.Fullscreen: case FullscreenMode.Fullscreen:
size = currentScreen.Bounds.Size; size = currentScreen.Bounds.Size;
location = currentScreen.Bounds.Location; location = currentScreen.Bounds.Location;
break; break;
case FullscreenMode.AllScreens: case FullscreenMode.AllScreens:
size = SystemInformation.VirtualScreen.Size; size = SystemInformation.VirtualScreen.Size;
location = SystemInformation.VirtualScreen.Location; location = SystemInformation.VirtualScreen.Location;
break; break;
} }
_mainForm.Size = size; _mainForm.Size = size;
_mainForm.Location = location; _mainForm.Location = location;
} }
public void SwitchBack() { public void SwitchBack() {
if (!IsFullscreen) if (!IsFullscreen)
return; return;
//Restore state //Restore state
_mainForm.FormBorderStyle = _preFullscreenBorderStyle; _mainForm.FormBorderStyle = _preFullscreenBorderStyle;
_mainForm.Location = _preFullscreenLocation; _mainForm.Location = _preFullscreenLocation;
_mainForm.ClientSize = _preFullscreenSize; _mainForm.ClientSize = _preFullscreenSize;
_mainForm.RefreshAspectRatio(); _mainForm.RefreshAspectRatio();
CommonCompleteSwitch(false); CommonCompleteSwitch(false);
} }
private void CommonCompleteSwitch(bool enabled) { private void CommonCompleteSwitch(bool enabled) {
//UI stuff switching //UI stuff switching
_mainForm.GlassMargins = (!enabled) ? new Padding(-1) : Padding.Empty; _mainForm.GlassMargins = (!enabled) ? new Padding(-1) : Padding.Empty;
_mainForm.TopMost = !enabled; _mainForm.TopMost = !enabled;
IsFullscreen = enabled; IsFullscreen = enabled;
Program.Platform.OnFormStateChange(_mainForm); Program.Platform.OnFormStateChange(_mainForm);
} }
public void Toggle() { public void Toggle() {
if (IsFullscreen) if (IsFullscreen)
SwitchBack(); SwitchBack();
else else
SwitchFullscreen(Settings.Default.GetFullscreenMode()); SwitchFullscreen(Settings.Default.GetFullscreenMode());
} }
} }
} }

View file

@ -1,39 +1,39 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Xml.Serialization; using System.Xml.Serialization;
using OnTopReplica.Properties; using OnTopReplica.Properties;
namespace OnTopReplica { namespace OnTopReplica {
/// <summary> /// <summary>
/// Describes a fullscreen mode. /// Describes a fullscreen mode.
/// </summary> /// </summary>
enum FullscreenMode { enum FullscreenMode {
Standard, Standard,
Fullscreen, Fullscreen,
AllScreens AllScreens
} }
static class FullscreenModeExtensions { static class FullscreenModeExtensions {
/// <summary> /// <summary>
/// Gets the fullscreen mode as an enumeration value. /// Gets the fullscreen mode as an enumeration value.
/// </summary> /// </summary>
public static FullscreenMode GetFullscreenMode(this Settings settings) { public static FullscreenMode GetFullscreenMode(this Settings settings) {
FullscreenMode retMode = FullscreenMode.Standard; FullscreenMode retMode = FullscreenMode.Standard;
Enum.TryParse<FullscreenMode>(settings.FullscreenMode, out retMode); Enum.TryParse<FullscreenMode>(settings.FullscreenMode, out retMode);
return retMode; return retMode;
} }
/// <summary> /// <summary>
/// Sets the fullscreen mode. /// Sets the fullscreen mode.
/// </summary> /// </summary>
public static void SetFullscreenMode(this Settings settings, FullscreenMode mode) { public static void SetFullscreenMode(this Settings settings, FullscreenMode mode) {
settings.FullscreenMode = mode.ToString(); settings.FullscreenMode = mode.ToString();
} }
} }
} }

View file

@ -1,74 +1,74 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica { namespace OnTopReplica {
/// <summary> /// <summary>
/// Common geometry extension methods. /// Common geometry extension methods.
/// </summary> /// </summary>
static class GeometryExtensions { static class GeometryExtensions {
/// <summary> /// <summary>
/// Returns the difference (offset vector) between two points. /// Returns the difference (offset vector) between two points.
/// </summary> /// </summary>
public static Point Difference(this Point a, Point b) { public static Point Difference(this Point a, Point b) {
return new Point(a.X - b.X, a.Y - b.Y); return new Point(a.X - b.X, a.Y - b.Y);
} }
/// <summary> /// <summary>
/// Expands a size value by a padding distance. /// Expands a size value by a padding distance.
/// </summary> /// </summary>
public static Size Expand(this Size size, Padding padding) { public static Size Expand(this Size size, Padding padding) {
return new Size(size.Width + padding.Horizontal, size.Height + padding.Vertical); return new Size(size.Width + padding.Horizontal, size.Height + padding.Vertical);
} }
/// <summary> /// <summary>
/// Expands a size value by a size distance. /// Expands a size value by a size distance.
/// </summary> /// </summary>
public static Size Expand(this Size size, Size expandSize) { public static Size Expand(this Size size, Size expandSize) {
return new Size(size.Width + expandSize.Width, size.Height + expandSize.Height); return new Size(size.Width + expandSize.Width, size.Height + expandSize.Height);
} }
/// <summary> /// <summary>
/// Computes the difference between two size values. /// Computes the difference between two size values.
/// </summary> /// </summary>
public static Size Difference(this Size a, Size b) { public static Size Difference(this Size a, Size b) {
return new Size(a.Width - b.Width, a.Height - b.Height); return new Size(a.Width - b.Width, a.Height - b.Height);
} }
/// <summary> /// <summary>
/// Ensures that the minimum size of a control respects a minimum /// Ensures that the minimum size of a control respects a minimum
/// client size area. /// client size area.
/// </summary> /// </summary>
/// <param name="ctrl">Control whose MinimumSize should be altered.</param> /// <param name="ctrl">Control whose MinimumSize should be altered.</param>
/// <param name="minimumClientSize">Minimum client size value to ensure.</param> /// <param name="minimumClientSize">Minimum client size value to ensure.</param>
public static void EnsureMinimumClientSize(this Control ctrl, Size minimumClientSize) { public static void EnsureMinimumClientSize(this Control ctrl, Size minimumClientSize) {
Size offset = ctrl.Size.Difference(ctrl.ClientSize); Size offset = ctrl.Size.Difference(ctrl.ClientSize);
ctrl.MinimumSize = minimumClientSize.Expand(offset); ctrl.MinimumSize = minimumClientSize.Expand(offset);
} }
/// <summary> /// <summary>
/// Attempts to fit a size structure to another fixed destination size, by maintaining /// Attempts to fit a size structure to another fixed destination size, by maintaining
/// the original aspect ratio. /// the original aspect ratio.
/// </summary> /// </summary>
public static Size Fit(this Size sourceSize, Size destinationSize) { public static Size Fit(this Size sourceSize, Size destinationSize) {
double sourceRatio = (double)sourceSize.Width / (double)sourceSize.Height; double sourceRatio = (double)sourceSize.Width / (double)sourceSize.Height;
double clientRatio = (double)destinationSize.Width / (double)destinationSize.Height; double clientRatio = (double)destinationSize.Width / (double)destinationSize.Height;
Size ret; Size ret;
if (sourceRatio >= clientRatio) { if (sourceRatio >= clientRatio) {
ret = new Size(destinationSize.Width, (int)((double)destinationSize.Width / sourceRatio)); ret = new Size(destinationSize.Width, (int)((double)destinationSize.Width / sourceRatio));
} }
else { else {
ret = new Size((int)((double)destinationSize.Height * sourceRatio), destinationSize.Height); ret = new Size((int)((double)destinationSize.Height * sourceRatio), destinationSize.Height);
} }
return ret; return ret;
} }
} }
} }

View file

@ -1,56 +1,56 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica { namespace OnTopReplica {
class HotKeyTextBox : TextBox { class HotKeyTextBox : TextBox {
protected override void OnCreateControl() { protected override void OnCreateControl() {
ReadOnly = true; ReadOnly = true;
base.OnCreateControl(); base.OnCreateControl();
} }
readonly Keys[] IgnoredKeys = new Keys[] { readonly Keys[] IgnoredKeys = new Keys[] {
Keys.ControlKey, Keys.ControlKey,
Keys.Control, Keys.Control,
Keys.Alt, Keys.Alt,
Keys.Menu, Keys.Menu,
Keys.ShiftKey, Keys.ShiftKey,
Keys.Shift, Keys.Shift,
Keys.LWin, Keys.LWin,
Keys.RWin Keys.RWin
}; };
readonly Keys[] CancelKeys = new Keys[] { readonly Keys[] CancelKeys = new Keys[] {
Keys.Back, Keys.Back,
Keys.Escape Keys.Escape
}; };
protected override void OnKeyUp(KeyEventArgs e) { protected override void OnKeyUp(KeyEventArgs e) {
if (CancelKeys.Contains(e.KeyCode)) { if (CancelKeys.Contains(e.KeyCode)) {
Text = string.Empty; Text = string.Empty;
} }
else if (!IgnoredKeys.Contains(e.KeyCode)) { else if (!IgnoredKeys.Contains(e.KeyCode)) {
var sb = new StringBuilder(); var sb = new StringBuilder();
if (e.Control) if (e.Control)
sb.Append("[CTRL]+"); sb.Append("[CTRL]+");
if (e.Alt) if (e.Alt)
sb.Append("[ALT]+"); sb.Append("[ALT]+");
if (e.Shift) if (e.Shift)
sb.Append("[SHIFT]+"); sb.Append("[SHIFT]+");
sb.Append(e.KeyCode.ToString()); sb.Append(e.KeyCode.ToString());
Text = sb.ToString(); Text = sb.ToString();
} }
e.Handled = true; e.Handled = true;
base.OnKeyUp(e); base.OnKeyUp(e);
} }
} }
} }

View file

@ -1,15 +1,15 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica { namespace OnTopReplica {
interface IMessagePumpProcessor : IDisposable { interface IMessagePumpProcessor : IDisposable {
void Initialize(MainForm form); void Initialize(MainForm form);
bool Process(ref Message msg); bool Process(ref Message msg);
} }
} }

View file

@ -1,77 +1,77 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using System.Drawing; using System.Drawing;
namespace OnTopReplica { namespace OnTopReplica {
class ImageComboBox : ComboBox { class ImageComboBox : ComboBox {
public ImageComboBox() { public ImageComboBox() {
DrawMode = DrawMode.OwnerDrawFixed; DrawMode = DrawMode.OwnerDrawFixed;
} }
protected override void OnDrawItem(DrawItemEventArgs ea) { protected override void OnDrawItem(DrawItemEventArgs ea) {
ea.DrawBackground(); ea.DrawBackground();
ea.DrawFocusRectangle(); ea.DrawFocusRectangle();
if (ea.Index == -1) if (ea.Index == -1)
return; return;
Rectangle bounds = ea.Bounds; Rectangle bounds = ea.Bounds;
var foreBrush = new SolidBrush(ea.ForeColor); var foreBrush = new SolidBrush(ea.ForeColor);
int textLeftBound = (IconList == null) ? bounds.Left : bounds.Left + IconList.ImageSize.Width; int textLeftBound = (IconList == null) ? bounds.Left : bounds.Left + IconList.ImageSize.Width;
var drawObject = Items[ea.Index]; var drawObject = Items[ea.Index];
if (drawObject is ImageComboBoxItem) { if (drawObject is ImageComboBoxItem) {
var drawItem = (ImageComboBoxItem)drawObject; var drawItem = (ImageComboBoxItem)drawObject;
if (drawItem.ImageListIndex != -1 && IconList != null) { if (drawItem.ImageListIndex != -1 && IconList != null) {
//ea.Graphics.FillRectangle(Brushes.Gray, bounds.Left, bounds.Top, IconList.ImageSize.Width, IconList.ImageSize.Height); //ea.Graphics.FillRectangle(Brushes.Gray, bounds.Left, bounds.Top, IconList.ImageSize.Width, IconList.ImageSize.Height);
ea.Graphics.DrawImage(IconList.Images[drawItem.ImageListIndex], bounds.Left, bounds.Top); ea.Graphics.DrawImage(IconList.Images[drawItem.ImageListIndex], bounds.Left, bounds.Top);
} }
ea.Graphics.DrawString(drawItem.Text, ea.Font, foreBrush, textLeftBound, bounds.Top); ea.Graphics.DrawString(drawItem.Text, ea.Font, foreBrush, textLeftBound, bounds.Top);
} }
else { else {
ea.Graphics.DrawString(drawObject.ToString(), ea.Font, foreBrush, textLeftBound, bounds.Top); ea.Graphics.DrawString(drawObject.ToString(), ea.Font, foreBrush, textLeftBound, bounds.Top);
} }
base.OnDrawItem(ea); base.OnDrawItem(ea);
} }
public ImageList IconList { get; set; } public ImageList IconList { get; set; }
} }
class ImageComboBoxItem { class ImageComboBoxItem {
public ImageComboBoxItem() { public ImageComboBoxItem() {
Text = ""; Text = "";
ImageListIndex = -1; ImageListIndex = -1;
} }
public ImageComboBoxItem(string text) { public ImageComboBoxItem(string text) {
if (text == null) if (text == null)
throw new ArgumentNullException(); throw new ArgumentNullException();
Text = text; Text = text;
ImageListIndex = -1; ImageListIndex = -1;
} }
public ImageComboBoxItem(string text, int imageListIndex) { public ImageComboBoxItem(string text, int imageListIndex) {
if (text == null) if (text == null)
throw new ArgumentNullException(); throw new ArgumentNullException();
Text = text; Text = text;
ImageListIndex = imageListIndex; ImageListIndex = imageListIndex;
} }
public string Text { get; private set; } public string Text { get; private set; }
public int ImageListIndex { get; private set; } public int ImageListIndex { get; private set; }
public object Tag { get; set; } public object Tag { get; set; }
} }
} }

View file

@ -1,54 +1,54 @@
Microsoft Reciprocal License (Ms-RL) Microsoft Reciprocal License (Ms-RL)
This license governs use of the accompanying software. If you use the This license governs use of the accompanying software. If you use the
software, you accept this license. If you do not accept the license, do not software, you accept this license. If you do not accept the license, do not
use the software. use the software.
1. Definitions 1. Definitions
The terms "reproduce," "reproduction," "derivative works," and "distribution" The terms "reproduce," "reproduction," "derivative works," and "distribution"
have the same meaning here as under U.S. copyright law. have the same meaning here as under U.S. copyright law.
A "contribution" is the original software, or any additions or changes to the A "contribution" is the original software, or any additions or changes to the
software. software.
A "contributor" is any person that distributes its contribution under this A "contributor" is any person that distributes its contribution under this
license. license.
"Licensed patents" are a contributor's patent claims that read directly on its "Licensed patents" are a contributor's patent claims that read directly on its
contribution. contribution.
2. Grant of Rights 2. Grant of Rights
(A) Copyright Grant- Subject to the terms of this license, including the (A) Copyright Grant- Subject to the terms of this license, including the
license conditions and limitations in section 3, each contributor grants you a license conditions and limitations in section 3, each contributor grants you a
non-exclusive, worldwide, royalty-free copyright license to reproduce its non-exclusive, worldwide, royalty-free copyright license to reproduce its
contribution, prepare derivative works of its contribution, and distribute its contribution, prepare derivative works of its contribution, and distribute its
contribution or any derivative works that you create. contribution or any derivative works that you create.
(B) Patent Grant- Subject to the terms of this license, including the license (B) Patent Grant- Subject to the terms of this license, including the license
conditions and limitations in section 3, each contributor grants you a conditions and limitations in section 3, each contributor grants you a
non-exclusive, worldwide, royalty-free license under its licensed patents to non-exclusive, worldwide, royalty-free license under its licensed patents to
make, have made, use, sell, offer for sale, import, and/or otherwise dispose make, have made, use, sell, offer for sale, import, and/or otherwise dispose
of its contribution in the software or derivative works of the contribution of its contribution in the software or derivative works of the contribution
in the software. in the software.
3. Conditions and Limitations 3. Conditions and Limitations
(A) Reciprocal Grants- For any file you distribute that contains code from the (A) Reciprocal Grants- For any file you distribute that contains code from the
software (in source code or binary format), you must provide recipients the software (in source code or binary format), you must provide recipients the
source code to that file along with a copy of this license, which license will source code to that file along with a copy of this license, which license will
govern that file. You may license other files that are entirely your own work govern that file. You may license other files that are entirely your own work
and do not contain code from the software under any terms you choose. and do not contain code from the software under any terms you choose.
(B) No Trademark License- This license does not grant you rights to use any (B) No Trademark License- This license does not grant you rights to use any
contributors' name, logo, or trademarks. contributors' name, logo, or trademarks.
(C) If you bring a patent claim against any contributor over patents that you (C) If you bring a patent claim against any contributor over patents that you
claim are infringed by the software, your patent license from such contributor claim are infringed by the software, your patent license from such contributor
to the software ends automatically. to the software ends automatically.
(D) If you distribute any portion of the software, you must retain all (D) If you distribute any portion of the software, you must retain all
copyright, patent, trademark, and attribution notices that are present in the copyright, patent, trademark, and attribution notices that are present in the
software. software.
(E) If you distribute any portion of the software in source code form, you may (E) If you distribute any portion of the software in source code form, you may
do so only under this license by including a complete copy of this license do so only under this license by including a complete copy of this license
with your distribution. If you distribute any portion of the software in with your distribution. If you distribute any portion of the software in
compiled or object code form, you may only do so under a license that complies compiled or object code form, you may only do so under a license that complies
with this license. with this license.
(F) The software is licensed "as-is." You bear the risk of using it. The (F) The software is licensed "as-is." You bear the risk of using it. The
contributors give no express warranties, guarantees or conditions. You may contributors give no express warranties, guarantees or conditions. You may
have additional consumer rights under your local laws which this license have additional consumer rights under your local laws which this license
cannot change. To the extent permitted under your local laws, the contributors cannot change. To the extent permitted under your local laws, the contributors
exclude the implied warranties of merchantability, fitness for a particular exclude the implied warranties of merchantability, fitness for a particular
purpose and non-infringement. purpose and non-infringement.

View file

@ -1,109 +1,109 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace OnTopReplica { namespace OnTopReplica {
static class Log { static class Log {
const string LogFileName = "lastrun.log.txt"; const string LogFileName = "lastrun.log.txt";
const string ConflictLogFileName = "run-{0}.log.txt"; const string ConflictLogFileName = "run-{0}.log.txt";
private readonly static StreamWriter Writer; private readonly static StreamWriter Writer;
static Log() { static Log() {
try { try {
var filepath = Path.Combine(AppPaths.PrivateRoamingFolderPath, LogFileName); var filepath = Path.Combine(AppPaths.PrivateRoamingFolderPath, LogFileName);
Writer = new StreamWriter(new FileStream(filepath, FileMode.Create)); Writer = new StreamWriter(new FileStream(filepath, FileMode.Create));
Writer.AutoFlush = true; Writer.AutoFlush = true;
} }
catch (Exception) { catch (Exception) {
try { try {
var filepath = Path.Combine(AppPaths.PrivateRoamingFolderPath, string.Format(ConflictLogFileName, System.Diagnostics.Process.GetCurrentProcess().Id)); var filepath = Path.Combine(AppPaths.PrivateRoamingFolderPath, string.Format(ConflictLogFileName, System.Diagnostics.Process.GetCurrentProcess().Id));
Writer = new StreamWriter(new FileStream(filepath, FileMode.Create)); Writer = new StreamWriter(new FileStream(filepath, FileMode.Create));
Writer.AutoFlush = true; Writer.AutoFlush = true;
} }
catch (Exception) { catch (Exception) {
//No fallback logging possible //No fallback logging possible
Writer = null; Writer = null;
} }
} }
} }
public static void Write(string message) { public static void Write(string message) {
WriteLine(message); WriteLine(message);
} }
public static void Write(string format, object arg0) { public static void Write(string format, object arg0) {
WriteLine(string.Format(format, arg0)); WriteLine(string.Format(format, arg0));
} }
public static void Write(string format, object arg0, object arg1) { public static void Write(string format, object arg0, object arg1) {
WriteLine(string.Format(format, arg0, arg1)); WriteLine(string.Format(format, arg0, arg1));
} }
public static void Write(string format, params object[] args) { public static void Write(string format, params object[] args) {
WriteLine(string.Format(format, args)); WriteLine(string.Format(format, args));
} }
public static void WriteDetails(string caption, string format, params object[] args) { public static void WriteDetails(string caption, string format, params object[] args) {
WriteLines(caption, string.Format(format, args)); WriteLines(caption, string.Format(format, args));
} }
public static void WriteException(string message, Exception exception) { public static void WriteException(string message, Exception exception) {
if (exception != null) { if (exception != null) {
WriteLines(message, exception.ToString()); WriteLines(message, exception.ToString());
} }
else { else {
WriteLines(message, "(No exception data.)"); WriteLines(message, "(No exception data.)");
} }
} }
private static void WriteLine(string message) { private static void WriteLine(string message) {
var s = string.Format("{0,-8:HH:mm:ss} {1}", DateTime.Now, message); var s = string.Format("{0,-8:HH:mm:ss} {1}", DateTime.Now, message);
AddToQueue(s); AddToQueue(s);
if (Writer != null) { if (Writer != null) {
Writer.WriteLine(s); Writer.WriteLine(s);
} }
} }
private static void WriteLines(params string[] messages) { private static void WriteLines(params string[] messages) {
if (messages.Length <= 0) if (messages.Length <= 0)
return; return;
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendFormat("{0,-8:HH:mm:ss} {1}", DateTime.Now, messages[0]); sb.AppendFormat("{0,-8:HH:mm:ss} {1}", DateTime.Now, messages[0]);
for (int i = 1; i < messages.Length; ++i) { for (int i = 1; i < messages.Length; ++i) {
sb.AppendLine(); sb.AppendLine();
sb.AppendFormat(" {0}", messages[i]); sb.AppendFormat(" {0}", messages[i]);
} }
AddToQueue(sb.ToString()); AddToQueue(sb.ToString());
if (Writer != null) { if (Writer != null) {
Writer.WriteLine(sb.ToString()); Writer.WriteLine(sb.ToString());
} }
} }
const int MaxQueueCapacity = 30; const int MaxQueueCapacity = 30;
private static Queue<string> _entriesQueue = new Queue<string>(MaxQueueCapacity); private static Queue<string> _entriesQueue = new Queue<string>(MaxQueueCapacity);
private static void AddToQueue(string entry){ private static void AddToQueue(string entry){
_entriesQueue.Enqueue(entry); _entriesQueue.Enqueue(entry);
while(_entriesQueue.Count > MaxQueueCapacity){ while(_entriesQueue.Count > MaxQueueCapacity){
_entriesQueue.Dequeue(); _entriesQueue.Dequeue();
} }
} }
public static IEnumerable<string> Queue { public static IEnumerable<string> Queue {
get { get {
return _entriesQueue; return _entriesQueue;
} }
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,461 +1,461 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Native; using OnTopReplica.Native;
using OnTopReplica.Properties; using OnTopReplica.Properties;
using OnTopReplica.StartupOptions; using OnTopReplica.StartupOptions;
using OnTopReplica.Update; using OnTopReplica.Update;
using OnTopReplica.WindowSeekers; using OnTopReplica.WindowSeekers;
using WindowsFormsAero.Dwm; using WindowsFormsAero.Dwm;
using WindowsFormsAero.TaskDialog; using WindowsFormsAero.TaskDialog;
namespace OnTopReplica { namespace OnTopReplica {
partial class MainForm : AspectRatioForm { partial class MainForm : AspectRatioForm {
//GUI elements //GUI elements
ThumbnailPanel _thumbnailPanel; ThumbnailPanel _thumbnailPanel;
//Managers //Managers
readonly MessagePumpManager _msgPumpManager = new MessagePumpManager(); readonly MessagePumpManager _msgPumpManager = new MessagePumpManager();
WindowListMenuManager _windowListManager; WindowListMenuManager _windowListManager;
public FullscreenFormManager FullscreenManager { get; private set; } public FullscreenFormManager FullscreenManager { get; private set; }
Options _startupOptions; Options _startupOptions;
public MainForm(Options startupOptions) { public MainForm(Options startupOptions) {
_startupOptions = startupOptions; _startupOptions = startupOptions;
FullscreenManager = new FullscreenFormManager(this); FullscreenManager = new FullscreenFormManager(this);
_quickRegionDrawingHandler = new ThumbnailPanel.RegionDrawnHandler(HandleQuickRegionDrawn); _quickRegionDrawingHandler = new ThumbnailPanel.RegionDrawnHandler(HandleQuickRegionDrawn);
//WinForms init pass //WinForms init pass
InitializeComponent(); InitializeComponent();
//Store default values //Store default values
DefaultNonClickTransparencyKey = this.TransparencyKey; DefaultNonClickTransparencyKey = this.TransparencyKey;
DefaultBorderStyle = this.FormBorderStyle; DefaultBorderStyle = this.FormBorderStyle;
//Thumbnail panel //Thumbnail panel
_thumbnailPanel = new ThumbnailPanel { _thumbnailPanel = new ThumbnailPanel {
Location = Point.Empty, Location = Point.Empty,
Dock = DockStyle.Fill Dock = DockStyle.Fill
}; };
_thumbnailPanel.CloneClick += new EventHandler<CloneClickEventArgs>(Thumbnail_CloneClick); _thumbnailPanel.CloneClick += new EventHandler<CloneClickEventArgs>(Thumbnail_CloneClick);
Controls.Add(_thumbnailPanel); Controls.Add(_thumbnailPanel);
//Set native renderer on context menus //Set native renderer on context menus
Asztal.Szótár.NativeToolStripRenderer.SetToolStripRenderer( Asztal.Szótár.NativeToolStripRenderer.SetToolStripRenderer(
menuContext, menuWindows, menuOpacity, menuResize, menuFullscreenContext menuContext, menuWindows, menuOpacity, menuResize, menuFullscreenContext
); );
//Set to Key event preview //Set to Key event preview
this.KeyPreview = true; this.KeyPreview = true;
Log.Write("Main form constructed"); Log.Write("Main form constructed");
} }
#region Event override #region Event override
protected override void OnHandleCreated(EventArgs e){ protected override void OnHandleCreated(EventArgs e){
base.OnHandleCreated(e); base.OnHandleCreated(e);
//Window init //Window init
KeepAspectRatio = false; KeepAspectRatio = false;
GlassMargins = new Padding(-1); GlassMargins = new Padding(-1);
//Managers //Managers
_msgPumpManager.Initialize(this); _msgPumpManager.Initialize(this);
_windowListManager = new WindowListMenuManager(this, menuWindows); _windowListManager = new WindowListMenuManager(this, menuWindows);
_windowListManager.ParentMenus = new System.Windows.Forms.ContextMenuStrip[] { _windowListManager.ParentMenus = new System.Windows.Forms.ContextMenuStrip[] {
menuContext, menuFullscreenContext menuContext, menuFullscreenContext
}; };
//Platform specific form initialization //Platform specific form initialization
Program.Platform.PostHandleFormInit(this); Program.Platform.PostHandleFormInit(this);
} }
protected override void OnShown(EventArgs e) { protected override void OnShown(EventArgs e) {
Log.Write("Main form shown"); Log.Write("Main form shown");
base.OnShown(e); base.OnShown(e);
//Apply startup options //Apply startup options
_startupOptions.Apply(this); _startupOptions.Apply(this);
} }
protected override void OnClosing(CancelEventArgs e) { protected override void OnClosing(CancelEventArgs e) {
Log.Write("Main form closing"); Log.Write("Main form closing");
base.OnClosing(e); base.OnClosing(e);
_msgPumpManager.Dispose(); _msgPumpManager.Dispose();
Program.Platform.CloseForm(this); Program.Platform.CloseForm(this);
} }
protected override void OnClosed(EventArgs e) { protected override void OnClosed(EventArgs e) {
Log.Write("Main form closed"); Log.Write("Main form closed");
base.OnClosed(e); base.OnClosed(e);
} }
protected override void OnMove(EventArgs e) { protected override void OnMove(EventArgs e) {
base.OnMove(e); base.OnMove(e);
AdjustSidePanelLocation(); AdjustSidePanelLocation();
} }
protected override void OnResizeEnd(EventArgs e) { protected override void OnResizeEnd(EventArgs e) {
base.OnResizeEnd(e); base.OnResizeEnd(e);
RefreshScreenLock(); RefreshScreenLock();
} }
protected override void OnResizing(EventArgs e) { protected override void OnResizing(EventArgs e) {
//Update aspect ratio from thumbnail while resizing (but do not refresh, resizing does that anyway) //Update aspect ratio from thumbnail while resizing (but do not refresh, resizing does that anyway)
if (_thumbnailPanel.IsShowingThumbnail) { if (_thumbnailPanel.IsShowingThumbnail) {
SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, false); SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, false);
} }
} }
protected override void OnActivated(EventArgs e) { protected override void OnActivated(EventArgs e) {
base.OnActivated(e); base.OnActivated(e);
//Deactivate click-through if form is reactivated //Deactivate click-through if form is reactivated
if (ClickThroughEnabled) { if (ClickThroughEnabled) {
ClickThroughEnabled = false; ClickThroughEnabled = false;
} }
Program.Platform.RestoreForm(this); Program.Platform.RestoreForm(this);
} }
protected override void OnDeactivate(EventArgs e) { protected override void OnDeactivate(EventArgs e) {
base.OnDeactivate(e); base.OnDeactivate(e);
//HACK: sometimes, even if TopMost is true, the window loses its "always on top" status. //HACK: sometimes, even if TopMost is true, the window loses its "always on top" status.
// This is a fix attempt that probably won't work... // This is a fix attempt that probably won't work...
if (!FullscreenManager.IsFullscreen) { //fullscreen mode doesn't use TopMost if (!FullscreenManager.IsFullscreen) { //fullscreen mode doesn't use TopMost
TopMost = false; TopMost = false;
TopMost = true; TopMost = true;
} }
} }
protected override void OnMouseWheel(MouseEventArgs e) { protected override void OnMouseWheel(MouseEventArgs e) {
base.OnMouseWheel(e); base.OnMouseWheel(e);
if (!FullscreenManager.IsFullscreen) { if (!FullscreenManager.IsFullscreen) {
if (_thumbnailPanel.IsShowingThumbnail) { if (_thumbnailPanel.IsShowingThumbnail) {
SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, false); SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, false);
} }
int change = (int)(e.Delta / 6.0); //assumes a mouse wheel "tick" is in the 80-120 range int change = (int)(e.Delta / 6.0); //assumes a mouse wheel "tick" is in the 80-120 range
AdjustSize(change); AdjustSize(change);
RefreshScreenLock(); RefreshScreenLock();
} }
} }
protected override void OnMouseDoubleClick(MouseEventArgs e) { protected override void OnMouseDoubleClick(MouseEventArgs e) {
base.OnMouseDoubleClick(e); base.OnMouseDoubleClick(e);
//This is handled by the WM_NCLBUTTONDBLCLK msg handler usually (because the GlassForm translates //This is handled by the WM_NCLBUTTONDBLCLK msg handler usually (because the GlassForm translates
//clicks on client to clicks on caption). But if fullscreen mode disables GlassForm dragging, we need //clicks on client to clicks on caption). But if fullscreen mode disables GlassForm dragging, we need
//this auxiliary handler to switch mode. //this auxiliary handler to switch mode.
FullscreenManager.Toggle(); FullscreenManager.Toggle();
} }
protected override void OnMouseClick(MouseEventArgs e) { protected override void OnMouseClick(MouseEventArgs e) {
base.OnMouseClick(e); base.OnMouseClick(e);
//Same story as above (OnMouseDoubleClick) //Same story as above (OnMouseDoubleClick)
if (e.Button == System.Windows.Forms.MouseButtons.Right) { if (e.Button == System.Windows.Forms.MouseButtons.Right) {
OpenContextMenu(null); OpenContextMenu(null);
} }
} }
private ThumbnailPanel.RegionDrawnHandler _quickRegionDrawingHandler; private ThumbnailPanel.RegionDrawnHandler _quickRegionDrawingHandler;
protected override void WndProc(ref Message m) { protected override void WndProc(ref Message m) {
if (_msgPumpManager != null) { if (_msgPumpManager != null) {
if (_msgPumpManager.PumpMessage(ref m)) { if (_msgPumpManager.PumpMessage(ref m)) {
return; return;
} }
} }
switch (m.Msg) { switch (m.Msg) {
case WM.NCRBUTTONUP: case WM.NCRBUTTONUP:
//Open context menu if right button clicked on caption (i.e. all of the window area because of glass) //Open context menu if right button clicked on caption (i.e. all of the window area because of glass)
if (m.WParam.ToInt32() == HT.CAPTION) { if (m.WParam.ToInt32() == HT.CAPTION) {
OpenContextMenu(null); OpenContextMenu(null);
m.Result = IntPtr.Zero; m.Result = IntPtr.Zero;
return; return;
} }
break; break;
case WM.NCLBUTTONDOWN: case WM.NCLBUTTONDOWN:
if ((ModifierKeys & Keys.Control) == Keys.Control && if ((ModifierKeys & Keys.Control) == Keys.Control &&
ThumbnailPanel.IsShowingThumbnail && ThumbnailPanel.IsShowingThumbnail &&
!ThumbnailPanel.DrawMouseRegions) { !ThumbnailPanel.DrawMouseRegions) {
ThumbnailPanel.EnableMouseRegionsDrawingWithMouseDown(); ThumbnailPanel.EnableMouseRegionsDrawingWithMouseDown();
ThumbnailPanel.RegionDrawn += _quickRegionDrawingHandler; ThumbnailPanel.RegionDrawn += _quickRegionDrawingHandler;
m.Result = IntPtr.Zero; m.Result = IntPtr.Zero;
return; return;
} }
break; break;
case WM.NCLBUTTONDBLCLK: case WM.NCLBUTTONDBLCLK:
//Toggle fullscreen mode if double click on caption (whole glass area) //Toggle fullscreen mode if double click on caption (whole glass area)
if (m.WParam.ToInt32() == HT.CAPTION) { if (m.WParam.ToInt32() == HT.CAPTION) {
FullscreenManager.Toggle(); FullscreenManager.Toggle();
m.Result = IntPtr.Zero; m.Result = IntPtr.Zero;
return; return;
} }
break; break;
case WM.NCHITTEST: case WM.NCHITTEST:
//Make transparent to hit-testing if in click through mode //Make transparent to hit-testing if in click through mode
if (ClickThroughEnabled) { if (ClickThroughEnabled) {
m.Result = (IntPtr)HT.TRANSPARENT; m.Result = (IntPtr)HT.TRANSPARENT;
RefreshClickThroughComeBack(); RefreshClickThroughComeBack();
return; return;
} }
break; break;
} }
base.WndProc(ref m); base.WndProc(ref m);
} }
private void HandleQuickRegionDrawn(object sender, ThumbnailRegion region) { private void HandleQuickRegionDrawn(object sender, ThumbnailRegion region) {
//Reset region drawing state //Reset region drawing state
ThumbnailPanel.DrawMouseRegions = false; ThumbnailPanel.DrawMouseRegions = false;
ThumbnailPanel.RegionDrawn -= _quickRegionDrawingHandler; ThumbnailPanel.RegionDrawn -= _quickRegionDrawingHandler;
SelectedThumbnailRegion = region; SelectedThumbnailRegion = region;
} }
#endregion #endregion
#region Keyboard event handling #region Keyboard event handling
protected override void OnKeyUp(KeyEventArgs e) { protected override void OnKeyUp(KeyEventArgs e) {
base.OnKeyUp(e); base.OnKeyUp(e);
//ALT //ALT
if (e.Modifiers == Keys.Alt) { if (e.Modifiers == Keys.Alt) {
if (e.KeyCode == Keys.Enter) { if (e.KeyCode == Keys.Enter) {
e.Handled = true; e.Handled = true;
FullscreenManager.Toggle(); FullscreenManager.Toggle();
} }
else if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1) { else if (e.KeyCode == Keys.D1 || e.KeyCode == Keys.NumPad1) {
FitToThumbnail(0.25); FitToThumbnail(0.25);
} }
else if (e.KeyCode == Keys.D2 || e.KeyCode == Keys.NumPad2) { else if (e.KeyCode == Keys.D2 || e.KeyCode == Keys.NumPad2) {
FitToThumbnail(0.5); FitToThumbnail(0.5);
} }
else if (e.KeyCode == Keys.D3 || e.KeyCode == Keys.NumPad3 || else if (e.KeyCode == Keys.D3 || e.KeyCode == Keys.NumPad3 ||
e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0) { e.KeyCode == Keys.D0 || e.KeyCode == Keys.NumPad0) {
FitToThumbnail(1.0); FitToThumbnail(1.0);
} }
else if (e.KeyCode == Keys.D4 || e.KeyCode == Keys.NumPad4) { else if (e.KeyCode == Keys.D4 || e.KeyCode == Keys.NumPad4) {
FitToThumbnail(2.0); FitToThumbnail(2.0);
} }
} }
//F11 Fullscreen switch //F11 Fullscreen switch
else if (e.KeyCode == Keys.F11) { else if (e.KeyCode == Keys.F11) {
e.Handled = true; e.Handled = true;
FullscreenManager.Toggle(); FullscreenManager.Toggle();
} }
//ESCAPE //ESCAPE
else if (e.KeyCode == Keys.Escape) { else if (e.KeyCode == Keys.Escape) {
//Disable click-through //Disable click-through
if (ClickThroughEnabled) { if (ClickThroughEnabled) {
ClickThroughEnabled = false; ClickThroughEnabled = false;
} }
//Toggle fullscreen //Toggle fullscreen
else if (FullscreenManager.IsFullscreen) { else if (FullscreenManager.IsFullscreen) {
FullscreenManager.SwitchBack(); FullscreenManager.SwitchBack();
} }
//Disable click forwarding //Disable click forwarding
else if (ClickForwardingEnabled) { else if (ClickForwardingEnabled) {
ClickForwardingEnabled = false; ClickForwardingEnabled = false;
} }
} }
} }
#endregion #endregion
#region Thumbnail operation #region Thumbnail operation
/// <summary> /// <summary>
/// Sets a new thumbnail. /// Sets a new thumbnail.
/// </summary> /// </summary>
/// <param name="handle">Handle to the window to clone.</param> /// <param name="handle">Handle to the window to clone.</param>
/// <param name="region">Region of the window to clone or null.</param> /// <param name="region">Region of the window to clone or null.</param>
public void SetThumbnail(WindowHandle handle, ThumbnailRegion region) { public void SetThumbnail(WindowHandle handle, ThumbnailRegion region) {
try { try {
Log.Write("Cloning window HWND {0} of class {1}", handle.Handle, handle.Class); Log.Write("Cloning window HWND {0} of class {1}", handle.Handle, handle.Class);
CurrentThumbnailWindowHandle = handle; CurrentThumbnailWindowHandle = handle;
_thumbnailPanel.SetThumbnailHandle(handle, region); _thumbnailPanel.SetThumbnailHandle(handle, region);
//Set aspect ratio (this will resize the form), do not refresh if in fullscreen //Set aspect ratio (this will resize the form), do not refresh if in fullscreen
SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, !FullscreenManager.IsFullscreen); SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, !FullscreenManager.IsFullscreen);
} }
catch (Exception ex) { catch (Exception ex) {
Log.WriteException("Unable to set new thumbnail", ex); Log.WriteException("Unable to set new thumbnail", ex);
ThumbnailError(ex, false, Strings.ErrorUnableToCreateThumbnail); ThumbnailError(ex, false, Strings.ErrorUnableToCreateThumbnail);
_thumbnailPanel.UnsetThumbnail(); _thumbnailPanel.UnsetThumbnail();
} }
} }
/// <summary> /// <summary>
/// Enables group mode on a list of window handles. /// Enables group mode on a list of window handles.
/// </summary> /// </summary>
/// <param name="handles">List of window handles.</param> /// <param name="handles">List of window handles.</param>
public void SetThumbnailGroup(IList<WindowHandle> handles) { public void SetThumbnailGroup(IList<WindowHandle> handles) {
if (handles.Count == 0) if (handles.Count == 0)
return; return;
//At last one thumbnail //At last one thumbnail
SetThumbnail(handles[0], null); SetThumbnail(handles[0], null);
//Handle if no real group //Handle if no real group
if (handles.Count == 1) if (handles.Count == 1)
return; return;
CurrentThumbnailWindowHandle = null; CurrentThumbnailWindowHandle = null;
_msgPumpManager.Get<MessagePumpProcessors.GroupSwitchManager>().EnableGroupMode(handles); _msgPumpManager.Get<MessagePumpProcessors.GroupSwitchManager>().EnableGroupMode(handles);
} }
/// <summary> /// <summary>
/// Disables the cloned thumbnail. /// Disables the cloned thumbnail.
/// </summary> /// </summary>
public void UnsetThumbnail() { public void UnsetThumbnail() {
//Unset handle //Unset handle
CurrentThumbnailWindowHandle = null; CurrentThumbnailWindowHandle = null;
_thumbnailPanel.UnsetThumbnail(); _thumbnailPanel.UnsetThumbnail();
//Disable aspect ratio //Disable aspect ratio
KeepAspectRatio = false; KeepAspectRatio = false;
} }
/// <summary> /// <summary>
/// Gets or sets the region displayed of the current thumbnail. /// Gets or sets the region displayed of the current thumbnail.
/// </summary> /// </summary>
public ThumbnailRegion SelectedThumbnailRegion { public ThumbnailRegion SelectedThumbnailRegion {
get { get {
if (!_thumbnailPanel.IsShowingThumbnail || !_thumbnailPanel.ConstrainToRegion) if (!_thumbnailPanel.IsShowingThumbnail || !_thumbnailPanel.ConstrainToRegion)
return null; return null;
return _thumbnailPanel.SelectedRegion; return _thumbnailPanel.SelectedRegion;
} }
set { set {
if (!_thumbnailPanel.IsShowingThumbnail) if (!_thumbnailPanel.IsShowingThumbnail)
return; return;
_thumbnailPanel.SelectedRegion = value; _thumbnailPanel.SelectedRegion = value;
SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, true); SetAspectRatio(_thumbnailPanel.ThumbnailPixelSize, true);
FixPositionAndSize(); FixPositionAndSize();
} }
} }
const int FixMargin = 10; const int FixMargin = 10;
/// <summary> /// <summary>
/// Fixes the form's position and size, ensuring it is fully displayed in the current screen. /// Fixes the form's position and size, ensuring it is fully displayed in the current screen.
/// </summary> /// </summary>
private void FixPositionAndSize() { private void FixPositionAndSize() {
var screen = Screen.FromControl(this); var screen = Screen.FromControl(this);
if (Width > screen.WorkingArea.Width) { if (Width > screen.WorkingArea.Width) {
Width = screen.WorkingArea.Width - FixMargin; Width = screen.WorkingArea.Width - FixMargin;
} }
if (Height > screen.WorkingArea.Height) { if (Height > screen.WorkingArea.Height) {
Height = screen.WorkingArea.Height - FixMargin; Height = screen.WorkingArea.Height - FixMargin;
} }
if (Location.X + Width > screen.WorkingArea.Right) { if (Location.X + Width > screen.WorkingArea.Right) {
Location = new Point(screen.WorkingArea.Right - Width - FixMargin, Location.Y); Location = new Point(screen.WorkingArea.Right - Width - FixMargin, Location.Y);
} }
if (Location.Y + Height > screen.WorkingArea.Bottom) { if (Location.Y + Height > screen.WorkingArea.Bottom) {
Location = new Point(Location.X, screen.WorkingArea.Bottom - Height - FixMargin); Location = new Point(Location.X, screen.WorkingArea.Bottom - Height - FixMargin);
} }
} }
private void ThumbnailError(Exception ex, bool suppress, string title) { private void ThumbnailError(Exception ex, bool suppress, string title) {
if (!suppress) { if (!suppress) {
ShowErrorDialog(title, Strings.ErrorGenericThumbnailHandleError, ex.Message); ShowErrorDialog(title, Strings.ErrorGenericThumbnailHandleError, ex.Message);
} }
UnsetThumbnail(); UnsetThumbnail();
} }
/// <summary>Automatically sizes the window in order to accomodate the thumbnail p times.</summary> /// <summary>Automatically sizes the window in order to accomodate the thumbnail p times.</summary>
/// <param name="p">Scale of the thumbnail to consider.</param> /// <param name="p">Scale of the thumbnail to consider.</param>
private void FitToThumbnail(double p) { private void FitToThumbnail(double p) {
try { try {
Size originalSize = _thumbnailPanel.ThumbnailPixelSize; Size originalSize = _thumbnailPanel.ThumbnailPixelSize;
Size fittedSize = new Size((int)(originalSize.Width * p), (int)(originalSize.Height * p)); Size fittedSize = new Size((int)(originalSize.Width * p), (int)(originalSize.Height * p));
ClientSize = fittedSize; ClientSize = fittedSize;
RefreshScreenLock(); RefreshScreenLock();
} }
catch (Exception ex) { catch (Exception ex) {
ThumbnailError(ex, false, Strings.ErrorUnableToFit); ThumbnailError(ex, false, Strings.ErrorUnableToFit);
} }
} }
#endregion #endregion
#region Accessors #region Accessors
/// <summary> /// <summary>
/// Gets the form's thumbnail panel. /// Gets the form's thumbnail panel.
/// </summary> /// </summary>
public ThumbnailPanel ThumbnailPanel { public ThumbnailPanel ThumbnailPanel {
get { get {
return _thumbnailPanel; return _thumbnailPanel;
} }
} }
/// <summary> /// <summary>
/// Gets the form's message pump manager. /// Gets the form's message pump manager.
/// </summary> /// </summary>
public MessagePumpManager MessagePumpManager { public MessagePumpManager MessagePumpManager {
get { get {
return _msgPumpManager; return _msgPumpManager;
} }
} }
/// <summary> /// <summary>
/// Gets the form's window list drop down menu. /// Gets the form's window list drop down menu.
/// </summary> /// </summary>
public ContextMenuStrip MenuWindows { public ContextMenuStrip MenuWindows {
get { get {
return menuWindows; return menuWindows;
} }
} }
/// <summary> /// <summary>
/// Retrieves the window handle of the currently cloned thumbnail. /// Retrieves the window handle of the currently cloned thumbnail.
/// </summary> /// </summary>
public WindowHandle CurrentThumbnailWindowHandle { public WindowHandle CurrentThumbnailWindowHandle {
get; get;
private set; private set;
} }
#endregion #endregion
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -1,93 +1,93 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using System.Drawing; using System.Drawing;
namespace OnTopReplica { namespace OnTopReplica {
partial class MainForm { partial class MainForm {
//SidePanel _currentSidePanel = null; //SidePanel _currentSidePanel = null;
SidePanelContainer _sidePanelContainer = null; SidePanelContainer _sidePanelContainer = null;
/// <summary> /// <summary>
/// Opens a new side panel. /// Opens a new side panel.
/// </summary> /// </summary>
/// <param name="panel">The side panel to embed.</param> /// <param name="panel">The side panel to embed.</param>
public void SetSidePanel(SidePanel panel) { public void SetSidePanel(SidePanel panel) {
if (IsSidePanelOpen) { if (IsSidePanelOpen) {
CloseSidePanel(); CloseSidePanel();
} }
_sidePanelContainer = new SidePanelContainer(this); _sidePanelContainer = new SidePanelContainer(this);
_sidePanelContainer.SetSidePanel(panel); _sidePanelContainer.SetSidePanel(panel);
_sidePanelContainer.Location = ComputeSidePanelLocation(_sidePanelContainer); _sidePanelContainer.Location = ComputeSidePanelLocation(_sidePanelContainer);
_sidePanelContainer.Show(this); _sidePanelContainer.Show(this);
} }
/// <summary> /// <summary>
/// Closes the current side panel. /// Closes the current side panel.
/// </summary> /// </summary>
public void CloseSidePanel() { public void CloseSidePanel() {
if (_sidePanelContainer == null || _sidePanelContainer.IsDisposed) { if (_sidePanelContainer == null || _sidePanelContainer.IsDisposed) {
_sidePanelContainer = null; _sidePanelContainer = null;
return; return;
} }
_sidePanelContainer.Hide(); _sidePanelContainer.Hide();
_sidePanelContainer.FreeSidePanel(); _sidePanelContainer.FreeSidePanel();
} }
/// <summary> /// <summary>
/// Gets whether a side panel is currently shown. /// Gets whether a side panel is currently shown.
/// </summary> /// </summary>
public bool IsSidePanelOpen { public bool IsSidePanelOpen {
get { get {
if (_sidePanelContainer == null) if (_sidePanelContainer == null)
return false; return false;
if (_sidePanelContainer.IsDisposed) { if (_sidePanelContainer.IsDisposed) {
_sidePanelContainer = null; _sidePanelContainer = null;
return false; return false;
} }
return _sidePanelContainer.Visible; return _sidePanelContainer.Visible;
} }
} }
/// <summary> /// <summary>
/// Moves the side panel based on the main form's current location. /// Moves the side panel based on the main form's current location.
/// </summary> /// </summary>
protected void AdjustSidePanelLocation() { protected void AdjustSidePanelLocation() {
if (!IsSidePanelOpen) if (!IsSidePanelOpen)
return; return;
_sidePanelContainer.Location = ComputeSidePanelLocation(_sidePanelContainer); _sidePanelContainer.Location = ComputeSidePanelLocation(_sidePanelContainer);
} }
/// <summary> /// <summary>
/// Computes the target location of a side panel form that ensures it is visible on the current /// Computes the target location of a side panel form that ensures it is visible on the current
/// screen that contains the main form. /// screen that contains the main form.
/// </summary> /// </summary>
private Point ComputeSidePanelLocation(Form sidePanel) { private Point ComputeSidePanelLocation(Form sidePanel) {
//Check if moving the panel on the form's right would put it off-screen //Check if moving the panel on the form's right would put it off-screen
var screen = Screen.FromControl(this); var screen = Screen.FromControl(this);
if (Location.X + Width + sidePanel.Width > screen.WorkingArea.Right) { if (Location.X + Width + sidePanel.Width > screen.WorkingArea.Right) {
return new Point(Location.X - sidePanel.Width, Location.Y); return new Point(Location.X - sidePanel.Width, Location.Y);
} }
else { else {
return new Point(Location.X + Width, Location.Y); return new Point(Location.X + Width, Location.Y);
} }
} }
void SidePanel_RequestClosing(object sender, EventArgs e) { void SidePanel_RequestClosing(object sender, EventArgs e) {
CloseSidePanel(); CloseSidePanel();
} }
void Thumbnail_CloneClick(object sender, CloneClickEventArgs e) { void Thumbnail_CloneClick(object sender, CloneClickEventArgs e) {
Win32Helper.InjectFakeMouseClick(CurrentThumbnailWindowHandle.Handle, e); Win32Helper.InjectFakeMouseClick(CurrentThumbnailWindowHandle.Handle, e);
} }
} }
} }

View file

@ -1,167 +1,167 @@
using OnTopReplica.Native; using OnTopReplica.Native;
using OnTopReplica.Properties; using OnTopReplica.Properties;
using System; using System;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using WindowsFormsAero.TaskDialog; using WindowsFormsAero.TaskDialog;
namespace OnTopReplica { namespace OnTopReplica {
//Contains some feature implementations of MainForm //Contains some feature implementations of MainForm
partial class MainForm { partial class MainForm {
#region Click forwarding #region Click forwarding
public bool ClickForwardingEnabled { public bool ClickForwardingEnabled {
get { get {
return _thumbnailPanel.ReportThumbnailClicks; return _thumbnailPanel.ReportThumbnailClicks;
} }
set { set {
if (value && Settings.Default.FirstTimeClickForwarding) { if (value && Settings.Default.FirstTimeClickForwarding) {
TaskDialog dlg = new TaskDialog(Strings.InfoClickForwarding, Strings.InfoClickForwardingTitle, Strings.InfoClickForwardingContent) { TaskDialog dlg = new TaskDialog(Strings.InfoClickForwarding, Strings.InfoClickForwardingTitle, Strings.InfoClickForwardingContent) {
CommonButtons = CommonButton.Yes | CommonButton.No CommonButtons = CommonButton.Yes | CommonButton.No
}; };
if (dlg.Show(this).CommonButton == CommonButtonResult.No) if (dlg.Show(this).CommonButton == CommonButtonResult.No)
return; return;
Settings.Default.FirstTimeClickForwarding = false; Settings.Default.FirstTimeClickForwarding = false;
} }
_thumbnailPanel.ReportThumbnailClicks = value; _thumbnailPanel.ReportThumbnailClicks = value;
} }
} }
#endregion #endregion
#region Click-through #region Click-through
bool _clickThrough = false; bool _clickThrough = false;
readonly Color DefaultNonClickTransparencyKey; readonly Color DefaultNonClickTransparencyKey;
public bool ClickThroughEnabled { public bool ClickThroughEnabled {
get { get {
return _clickThrough; return _clickThrough;
} }
set { set {
TransparencyKey = (value) ? Color.Black : DefaultNonClickTransparencyKey; TransparencyKey = (value) ? Color.Black : DefaultNonClickTransparencyKey;
if (value) { if (value) {
//Re-force as top most (always helps in some cases) //Re-force as top most (always helps in some cases)
TopMost = false; TopMost = false;
this.Activate(); this.Activate();
TopMost = true; TopMost = true;
} }
_clickThrough = value; _clickThrough = value;
} }
} }
//Must NOT be equal to any other valid opacity value //Must NOT be equal to any other valid opacity value
const double ClickThroughHoverOpacity = 0.6; const double ClickThroughHoverOpacity = 0.6;
Timer _clickThroughComeBackTimer = null; Timer _clickThroughComeBackTimer = null;
long _clickThroughComeBackTicks; long _clickThroughComeBackTicks;
const int ClickThroughComeBackTimerInterval = 1000; const int ClickThroughComeBackTimerInterval = 1000;
/// <summary> /// <summary>
/// When the mouse hovers over a fully opaque click-through form, /// When the mouse hovers over a fully opaque click-through form,
/// this fades the form to semi-transparency /// this fades the form to semi-transparency
/// and starts a timeout to get back to full opacity. /// and starts a timeout to get back to full opacity.
/// </summary> /// </summary>
private void RefreshClickThroughComeBack() { private void RefreshClickThroughComeBack() {
if (this.Opacity == 1.0) { if (this.Opacity == 1.0) {
this.Opacity = ClickThroughHoverOpacity; this.Opacity = ClickThroughHoverOpacity;
} }
if (_clickThroughComeBackTimer == null) { if (_clickThroughComeBackTimer == null) {
_clickThroughComeBackTimer = new Timer(); _clickThroughComeBackTimer = new Timer();
_clickThroughComeBackTimer.Tick += _clickThroughComeBackTimer_Tick; _clickThroughComeBackTimer.Tick += _clickThroughComeBackTimer_Tick;
_clickThroughComeBackTimer.Interval = ClickThroughComeBackTimerInterval; _clickThroughComeBackTimer.Interval = ClickThroughComeBackTimerInterval;
} }
_clickThroughComeBackTicks = DateTime.UtcNow.Ticks; _clickThroughComeBackTicks = DateTime.UtcNow.Ticks;
_clickThroughComeBackTimer.Start(); _clickThroughComeBackTimer.Start();
} }
void _clickThroughComeBackTimer_Tick(object sender, EventArgs e) { void _clickThroughComeBackTimer_Tick(object sender, EventArgs e) {
var diff = DateTime.UtcNow.Subtract(new DateTime(_clickThroughComeBackTicks)); var diff = DateTime.UtcNow.Subtract(new DateTime(_clickThroughComeBackTicks));
if (diff.TotalSeconds > 2) { if (diff.TotalSeconds > 2) {
var mousePointer = WindowMethods.GetCursorPos(); var mousePointer = WindowMethods.GetCursorPos();
if (!this.ContainsMousePointer(mousePointer)) { if (!this.ContainsMousePointer(mousePointer)) {
if (this.Opacity == ClickThroughHoverOpacity) { if (this.Opacity == ClickThroughHoverOpacity) {
this.Opacity = 1.0; this.Opacity = 1.0;
} }
_clickThroughComeBackTimer.Stop(); _clickThroughComeBackTimer.Stop();
} }
} }
} }
#endregion #endregion
#region Chrome #region Chrome
readonly FormBorderStyle DefaultBorderStyle; // = FormBorderStyle.Sizable; // FormBorderStyle.SizableToolWindow; readonly FormBorderStyle DefaultBorderStyle; // = FormBorderStyle.Sizable; // FormBorderStyle.SizableToolWindow;
public bool IsChromeVisible { public bool IsChromeVisible {
get { get {
return (FormBorderStyle == DefaultBorderStyle); return (FormBorderStyle == DefaultBorderStyle);
} }
set { set {
//Cancel hiding chrome if no thumbnail is shown //Cancel hiding chrome if no thumbnail is shown
if (!value && !_thumbnailPanel.IsShowingThumbnail) if (!value && !_thumbnailPanel.IsShowingThumbnail)
return; return;
if (!value) { if (!value) {
Location = new Point { Location = new Point {
X = Location.X + SystemInformation.FrameBorderSize.Width, X = Location.X + SystemInformation.FrameBorderSize.Width,
Y = Location.Y + SystemInformation.FrameBorderSize.Height Y = Location.Y + SystemInformation.FrameBorderSize.Height
}; };
FormBorderStyle = FormBorderStyle.None; FormBorderStyle = FormBorderStyle.None;
} }
else if(value) { else if(value) {
Location = new Point { Location = new Point {
X = Location.X - SystemInformation.FrameBorderSize.Width, X = Location.X - SystemInformation.FrameBorderSize.Width,
Y = Location.Y - SystemInformation.FrameBorderSize.Height Y = Location.Y - SystemInformation.FrameBorderSize.Height
}; };
FormBorderStyle = DefaultBorderStyle; FormBorderStyle = DefaultBorderStyle;
} }
Program.Platform.OnFormStateChange(this); Program.Platform.OnFormStateChange(this);
Invalidate(); Invalidate();
} }
} }
#endregion #endregion
#region Position lock #region Position lock
ScreenPosition? _positionLock = null; ScreenPosition? _positionLock = null;
/// <summary> /// <summary>
/// Gets or sets the screen position where the window is currently locked in. /// Gets or sets the screen position where the window is currently locked in.
/// </summary> /// </summary>
public ScreenPosition? PositionLock { public ScreenPosition? PositionLock {
get { get {
return _positionLock; return _positionLock;
} }
set { set {
if (value != null) if (value != null)
this.SetScreenPosition(value.Value); this.SetScreenPosition(value.Value);
_positionLock = value; _positionLock = value;
} }
} }
/// <summary> /// <summary>
/// Refreshes window position if in lock mode. /// Refreshes window position if in lock mode.
/// </summary> /// </summary>
private void RefreshScreenLock() { private void RefreshScreenLock() {
//If locked in position, move accordingly //If locked in position, move accordingly
if (PositionLock.HasValue) { if (PositionLock.HasValue) {
this.SetScreenPosition(PositionLock.Value); this.SetScreenPosition(PositionLock.Value);
} }
} }
#endregion #endregion
} }
} }

View file

@ -1,117 +1,117 @@
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using WindowsFormsAero.TaskDialog; using WindowsFormsAero.TaskDialog;
namespace OnTopReplica { namespace OnTopReplica {
partial class MainForm { partial class MainForm {
/// <summary> /// <summary>
/// Opens the context menu. /// Opens the context menu.
/// </summary> /// </summary>
/// <param name="position">Optional position of the mouse, relative to which the menu is shown.</param> /// <param name="position">Optional position of the mouse, relative to which the menu is shown.</param>
public void OpenContextMenu(Point? position) { public void OpenContextMenu(Point? position) {
Point menuPosition = MousePosition; Point menuPosition = MousePosition;
if (position.HasValue) if (position.HasValue)
menuPosition = position.Value; menuPosition = position.Value;
if (FullscreenManager.IsFullscreen) { if (FullscreenManager.IsFullscreen) {
menuFullscreenContext.Show(menuPosition); menuFullscreenContext.Show(menuPosition);
} }
else { else {
menuContext.Show(menuPosition); menuContext.Show(menuPosition);
} }
} }
/// <summary> /// <summary>
/// Gets the window's vertical chrome size. /// Gets the window's vertical chrome size.
/// </summary> /// </summary>
public int ChromeBorderVertical { public int ChromeBorderVertical {
get { get {
if (IsChromeVisible) if (IsChromeVisible)
return SystemInformation.FrameBorderSize.Height; return SystemInformation.FrameBorderSize.Height;
else else
return 0; return 0;
} }
} }
/// <summary> /// <summary>
/// Gets the window's horizontal chrome size. /// Gets the window's horizontal chrome size.
/// </summary> /// </summary>
public int ChromeBorderHorizontal { public int ChromeBorderHorizontal {
get { get {
if (IsChromeVisible) if (IsChromeVisible)
return SystemInformation.FrameBorderSize.Width; return SystemInformation.FrameBorderSize.Width;
else else
return 0; return 0;
} }
} }
/// <summary> /// <summary>
/// Displays an error task dialog. /// Displays an error task dialog.
/// </summary> /// </summary>
/// <param name="mainInstruction">Main instruction of the error dialog.</param> /// <param name="mainInstruction">Main instruction of the error dialog.</param>
/// <param name="explanation">Detailed informations about the error.</param> /// <param name="explanation">Detailed informations about the error.</param>
/// <param name="errorMessage">Expanded error codes/messages.</param> /// <param name="errorMessage">Expanded error codes/messages.</param>
private void ShowErrorDialog(string mainInstruction, string explanation, string errorMessage) { private void ShowErrorDialog(string mainInstruction, string explanation, string errorMessage) {
TaskDialog dlg = new TaskDialog(mainInstruction, Strings.ErrorGenericTitle, explanation) { TaskDialog dlg = new TaskDialog(mainInstruction, Strings.ErrorGenericTitle, explanation) {
CommonIcon = CommonIcon.Stop, CommonIcon = CommonIcon.Stop,
IsExpanded = false IsExpanded = false
}; };
if (!string.IsNullOrEmpty(errorMessage)) { if (!string.IsNullOrEmpty(errorMessage)) {
dlg.ExpandedInformation = Strings.ErrorGenericInfoText + errorMessage; dlg.ExpandedInformation = Strings.ErrorGenericInfoText + errorMessage;
dlg.ExpandedControlText = Strings.ErrorGenericInfoButton; dlg.ExpandedControlText = Strings.ErrorGenericInfoButton;
} }
dlg.Show(this); dlg.Show(this);
} }
/// <summary> /// <summary>
/// Ensures that the main form is visible (either closing the fullscreen mode or reactivating from task icon). /// Ensures that the main form is visible (either closing the fullscreen mode or reactivating from task icon).
/// </summary> /// </summary>
public void EnsureMainFormVisible() { public void EnsureMainFormVisible() {
//Reset special modes //Reset special modes
FullscreenManager.SwitchBack(); FullscreenManager.SwitchBack();
ClickThroughEnabled = false; ClickThroughEnabled = false;
//Restore main form in a platform-dependent method //Restore main form in a platform-dependent method
Program.Platform.RestoreForm(this); Program.Platform.RestoreForm(this);
} }
/// <summary> /// <summary>
/// Opens a confirmation dialog to confirm whether to reset the main form or not. /// Opens a confirmation dialog to confirm whether to reset the main form or not.
/// </summary> /// </summary>
public void ResetMainFormWithConfirmation() { public void ResetMainFormWithConfirmation() {
var dlg = new TaskDialog(Strings.AskReset, Strings.AskResetTitle, Strings.AskResetContent); var dlg = new TaskDialog(Strings.AskReset, Strings.AskResetTitle, Strings.AskResetContent);
dlg.UseCommandLinks = true; dlg.UseCommandLinks = true;
dlg.CustomButtons = new CustomButton[] { dlg.CustomButtons = new CustomButton[] {
new CustomButton(CommonButtonResult.OK, Strings.AskResetButtonOk), new CustomButton(CommonButtonResult.OK, Strings.AskResetButtonOk),
new CustomButton(CommonButtonResult.Cancel, Strings.ButtonCancel) new CustomButton(CommonButtonResult.Cancel, Strings.ButtonCancel)
}; };
dlg.CommonIcon = CommonIcon.Information; dlg.CommonIcon = CommonIcon.Information;
if (dlg.Show(this).CommonButton == CommonButtonResult.OK) { if (dlg.Show(this).CommonButton == CommonButtonResult.OK) {
ResetMainForm(); ResetMainForm();
} }
} }
/// <summary> /// <summary>
/// Resets the main form to its initial state. /// Resets the main form to its initial state.
/// </summary> /// </summary>
public void ResetMainForm() { public void ResetMainForm() {
//Reset form settings //Reset form settings
UnsetThumbnail(); UnsetThumbnail();
CloseSidePanel(); CloseSidePanel();
//Reset location and size (edge of the screen, min size) //Reset location and size (edge of the screen, min size)
Point nuLoc = Screen.PrimaryScreen.WorkingArea.Location; Point nuLoc = Screen.PrimaryScreen.WorkingArea.Location;
nuLoc.Offset(40, 40); nuLoc.Offset(40, 40);
Location = nuLoc; Location = nuLoc;
Size = new Size(240, 220); Size = new Size(240, 220);
this.Show(); this.Show();
this.Activate(); this.Activate();
} }
} }
} }

View file

@ -1,202 +1,202 @@
using System; using System;
using System.ComponentModel; using System.ComponentModel;
using System.Drawing; using System.Drawing;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Properties; using OnTopReplica.Properties;
using WindowsFormsAero.TaskDialog; using WindowsFormsAero.TaskDialog;
using OnTopReplica.SidePanels; using OnTopReplica.SidePanels;
namespace OnTopReplica { namespace OnTopReplica {
partial class MainForm { partial class MainForm {
private void Menu_opening(object sender, CancelEventArgs e) { private void Menu_opening(object sender, CancelEventArgs e) {
//Cancel if currently in "fullscreen" mode or a side panel is open //Cancel if currently in "fullscreen" mode or a side panel is open
if (FullscreenManager.IsFullscreen || IsSidePanelOpen) { if (FullscreenManager.IsFullscreen || IsSidePanelOpen) {
e.Cancel = true; e.Cancel = true;
return; return;
} }
bool showing = _thumbnailPanel.IsShowingThumbnail; bool showing = _thumbnailPanel.IsShowingThumbnail;
selectRegionToolStripMenuItem.Enabled = showing; selectRegionToolStripMenuItem.Enabled = showing;
switchToWindowToolStripMenuItem.Enabled = showing; switchToWindowToolStripMenuItem.Enabled = showing;
resizeToolStripMenuItem.Enabled = showing; resizeToolStripMenuItem.Enabled = showing;
chromeToolStripMenuItem.Checked = IsChromeVisible; chromeToolStripMenuItem.Checked = IsChromeVisible;
clickForwardingToolStripMenuItem.Checked = ClickForwardingEnabled; clickForwardingToolStripMenuItem.Checked = ClickForwardingEnabled;
chromeToolStripMenuItem.Enabled = showing; chromeToolStripMenuItem.Enabled = showing;
clickThroughToolStripMenuItem.Enabled = showing; clickThroughToolStripMenuItem.Enabled = showing;
clickForwardingToolStripMenuItem.Enabled = showing; clickForwardingToolStripMenuItem.Enabled = showing;
} }
private void Menu_Switch_click(object sender, EventArgs e) { private void Menu_Switch_click(object sender, EventArgs e) {
if (CurrentThumbnailWindowHandle == null) if (CurrentThumbnailWindowHandle == null)
return; return;
Program.Platform.HideForm(this); Program.Platform.HideForm(this);
Native.WindowManagerMethods.SetForegroundWindow(CurrentThumbnailWindowHandle.Handle); Native.WindowManagerMethods.SetForegroundWindow(CurrentThumbnailWindowHandle.Handle);
} }
private void Menu_Advanced_opening(object sender, EventArgs e) { private void Menu_Advanced_opening(object sender, EventArgs e) {
restoreLastClonedWindowToolStripMenuItem.Checked = Settings.Default.RestoreLastWindow; restoreLastClonedWindowToolStripMenuItem.Checked = Settings.Default.RestoreLastWindow;
} }
private void Menu_GroupSwitchMode_click(object sender, EventArgs e) { private void Menu_GroupSwitchMode_click(object sender, EventArgs e) {
SetSidePanel(new SidePanels.GroupSwitchPanel()); SetSidePanel(new SidePanels.GroupSwitchPanel());
} }
private void Menu_RestoreLastWindow_click(object sender, EventArgs e) { private void Menu_RestoreLastWindow_click(object sender, EventArgs e) {
Settings.Default.RestoreLastWindow = !Settings.Default.RestoreLastWindow; Settings.Default.RestoreLastWindow = !Settings.Default.RestoreLastWindow;
} }
private void Menu_ClickForwarding_click(object sender, EventArgs e) { private void Menu_ClickForwarding_click(object sender, EventArgs e) {
ClickForwardingEnabled = !ClickForwardingEnabled; ClickForwardingEnabled = !ClickForwardingEnabled;
} }
private void Menu_ClickThrough_click(object sender, EventArgs e) { private void Menu_ClickThrough_click(object sender, EventArgs e) {
ClickThroughEnabled = true; ClickThroughEnabled = true;
} }
private void Menu_Opacity_opening(object sender, CancelEventArgs e) { private void Menu_Opacity_opening(object sender, CancelEventArgs e) {
ToolStripMenuItem[] items = { ToolStripMenuItem[] items = {
toolStripMenuItem1, toolStripMenuItem1,
toolStripMenuItem2, toolStripMenuItem2,
toolStripMenuItem3, toolStripMenuItem3,
toolStripMenuItem4 toolStripMenuItem4
}; };
foreach (ToolStripMenuItem i in items) { foreach (ToolStripMenuItem i in items) {
if (((double)i.Tag) == this.Opacity) if (((double)i.Tag) == this.Opacity)
i.Checked = true; i.Checked = true;
else else
i.Checked = false; i.Checked = false;
} }
} }
private void Menu_Opacity_click(object sender, EventArgs e) { private void Menu_Opacity_click(object sender, EventArgs e) {
ToolStripMenuItem tsi = (ToolStripMenuItem)sender; ToolStripMenuItem tsi = (ToolStripMenuItem)sender;
if (this.Visible) { if (this.Visible) {
//Target opacity is stored in the item's tag //Target opacity is stored in the item's tag
this.Opacity = (double)tsi.Tag; this.Opacity = (double)tsi.Tag;
Program.Platform.OnFormStateChange(this); Program.Platform.OnFormStateChange(this);
} }
} }
private void Menu_Region_click(object sender, EventArgs e) { private void Menu_Region_click(object sender, EventArgs e) {
SetSidePanel(new OnTopReplica.SidePanels.RegionPanel()); SetSidePanel(new OnTopReplica.SidePanels.RegionPanel());
} }
private void Menu_Resize_opening(object sender, CancelEventArgs e) { private void Menu_Resize_opening(object sender, CancelEventArgs e) {
if (!_thumbnailPanel.IsShowingThumbnail) if (!_thumbnailPanel.IsShowingThumbnail)
e.Cancel = true; e.Cancel = true;
restorePositionAndSizeToolStripMenuItem.Checked = Settings.Default.RestoreSizeAndPosition; restorePositionAndSizeToolStripMenuItem.Checked = Settings.Default.RestoreSizeAndPosition;
} }
private void Menu_Resize_Double(object sender, EventArgs e) { private void Menu_Resize_Double(object sender, EventArgs e) {
FitToThumbnail(2.0); FitToThumbnail(2.0);
} }
private void Menu_Resize_FitToWindow(object sender, EventArgs e) { private void Menu_Resize_FitToWindow(object sender, EventArgs e) {
FitToThumbnail(1.0); FitToThumbnail(1.0);
} }
private void Menu_Resize_Half(object sender, EventArgs e) { private void Menu_Resize_Half(object sender, EventArgs e) {
FitToThumbnail(0.5); FitToThumbnail(0.5);
} }
private void Menu_Resize_Quarter(object sender, EventArgs e) { private void Menu_Resize_Quarter(object sender, EventArgs e) {
FitToThumbnail(0.25); FitToThumbnail(0.25);
} }
private void Menu_Resize_Fullscreen(object sender, EventArgs e) { private void Menu_Resize_Fullscreen(object sender, EventArgs e) {
FullscreenManager.SwitchFullscreen(); FullscreenManager.SwitchFullscreen();
} }
private void Menu_Resize_RecallPosition_click(object sender, EventArgs e) { private void Menu_Resize_RecallPosition_click(object sender, EventArgs e) {
Settings.Default.RestoreSizeAndPosition = !Settings.Default.RestoreSizeAndPosition; Settings.Default.RestoreSizeAndPosition = !Settings.Default.RestoreSizeAndPosition;
} }
private void Menu_Position_Opening(object sender, EventArgs e) { private void Menu_Position_Opening(object sender, EventArgs e) {
disabledToolStripMenuItem.Checked = (PositionLock == null); disabledToolStripMenuItem.Checked = (PositionLock == null);
topLeftToolStripMenuItem.Checked = (PositionLock == ScreenPosition.TopLeft); topLeftToolStripMenuItem.Checked = (PositionLock == ScreenPosition.TopLeft);
topRightToolStripMenuItem.Checked = (PositionLock == ScreenPosition.TopRight); topRightToolStripMenuItem.Checked = (PositionLock == ScreenPosition.TopRight);
centerToolStripMenuItem.Checked = (PositionLock == ScreenPosition.Center); centerToolStripMenuItem.Checked = (PositionLock == ScreenPosition.Center);
bottomLeftToolStripMenuItem.Checked = (PositionLock == ScreenPosition.BottomLeft); bottomLeftToolStripMenuItem.Checked = (PositionLock == ScreenPosition.BottomLeft);
bottomRightToolStripMenuItem.Checked = (PositionLock == ScreenPosition.BottomRight); bottomRightToolStripMenuItem.Checked = (PositionLock == ScreenPosition.BottomRight);
} }
private void Menu_Position_Disable(object sender, EventArgs e) { private void Menu_Position_Disable(object sender, EventArgs e) {
PositionLock = null; PositionLock = null;
} }
private void Menu_Position_TopLeft(object sender, EventArgs e) { private void Menu_Position_TopLeft(object sender, EventArgs e) {
PositionLock = ScreenPosition.TopLeft; PositionLock = ScreenPosition.TopLeft;
} }
private void Menu_Position_TopRight(object sender, EventArgs e) { private void Menu_Position_TopRight(object sender, EventArgs e) {
PositionLock = ScreenPosition.TopRight; PositionLock = ScreenPosition.TopRight;
} }
private void Menu_Position_Center(object sender, EventArgs e) { private void Menu_Position_Center(object sender, EventArgs e) {
PositionLock = ScreenPosition.Center; PositionLock = ScreenPosition.Center;
} }
private void Menu_Position_BottomLeft(object sender, EventArgs e) { private void Menu_Position_BottomLeft(object sender, EventArgs e) {
PositionLock = ScreenPosition.BottomLeft; PositionLock = ScreenPosition.BottomLeft;
} }
private void Menu_Position_BottomRight(object sender, EventArgs e) { private void Menu_Position_BottomRight(object sender, EventArgs e) {
PositionLock = ScreenPosition.BottomRight; PositionLock = ScreenPosition.BottomRight;
} }
private void Menu_Reduce_click(object sender, EventArgs e) { private void Menu_Reduce_click(object sender, EventArgs e) {
//Hide form in a platform specific way //Hide form in a platform specific way
Program.Platform.HideForm(this); Program.Platform.HideForm(this);
} }
private void Menu_Chrome_click(object sender, EventArgs e) { private void Menu_Chrome_click(object sender, EventArgs e) {
IsChromeVisible = !IsChromeVisible; IsChromeVisible = !IsChromeVisible;
} }
private void Menu_Settings_click(object sender, EventArgs e) { private void Menu_Settings_click(object sender, EventArgs e) {
this.SetSidePanel(new OptionsPanel()); this.SetSidePanel(new OptionsPanel());
} }
private void Menu_About_click(object sender, EventArgs e) { private void Menu_About_click(object sender, EventArgs e) {
this.SetSidePanel(new AboutPanel()); this.SetSidePanel(new AboutPanel());
} }
private void Menu_Close_click(object sender, EventArgs e) { private void Menu_Close_click(object sender, EventArgs e) {
this.Close(); this.Close();
} }
private void Menu_Fullscreen_ExitFullscreen_click(object sender, EventArgs e) { private void Menu_Fullscreen_ExitFullscreen_click(object sender, EventArgs e) {
FullscreenManager.SwitchBack(); FullscreenManager.SwitchBack();
} }
private void Menu_Fullscreen_Mode_opening(object sender, EventArgs e) { private void Menu_Fullscreen_Mode_opening(object sender, EventArgs e) {
var mode = Settings.Default.GetFullscreenMode(); var mode = Settings.Default.GetFullscreenMode();
menuModeStandardToolStripMenuItem.Checked = (mode == FullscreenMode.Standard); menuModeStandardToolStripMenuItem.Checked = (mode == FullscreenMode.Standard);
menuModeFullscreenToolStripMenuItem.Checked = (mode == FullscreenMode.Fullscreen); menuModeFullscreenToolStripMenuItem.Checked = (mode == FullscreenMode.Fullscreen);
menuModeAllScreensToolStripMenuItem.Checked = (mode == FullscreenMode.AllScreens); menuModeAllScreensToolStripMenuItem.Checked = (mode == FullscreenMode.AllScreens);
} }
private void Menu_Fullscreen_Mode_Standard_click(object sender, EventArgs e) { private void Menu_Fullscreen_Mode_Standard_click(object sender, EventArgs e) {
Settings.Default.SetFullscreenMode(FullscreenMode.Standard); Settings.Default.SetFullscreenMode(FullscreenMode.Standard);
FullscreenManager.SwitchFullscreen(FullscreenMode.Standard); FullscreenManager.SwitchFullscreen(FullscreenMode.Standard);
} }
private void Menu_Fullscreen_Mode_Fullscreen_click(object sender, EventArgs e) { private void Menu_Fullscreen_Mode_Fullscreen_click(object sender, EventArgs e) {
Settings.Default.SetFullscreenMode(FullscreenMode.Fullscreen); Settings.Default.SetFullscreenMode(FullscreenMode.Fullscreen);
FullscreenManager.SwitchFullscreen(FullscreenMode.Fullscreen); FullscreenManager.SwitchFullscreen(FullscreenMode.Fullscreen);
} }
private void Menu_Fullscreen_Mode_AllScreens_click(object sender, EventArgs e) { private void Menu_Fullscreen_Mode_AllScreens_click(object sender, EventArgs e) {
Settings.Default.SetFullscreenMode(FullscreenMode.AllScreens); Settings.Default.SetFullscreenMode(FullscreenMode.AllScreens);
FullscreenManager.SwitchFullscreen(FullscreenMode.AllScreens); FullscreenManager.SwitchFullscreen(FullscreenMode.AllScreens);
} }
} }
} }

View file

@ -1,85 +1,85 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.MessagePumpProcessors; using OnTopReplica.MessagePumpProcessors;
using OnTopReplica.Native; using OnTopReplica.Native;
namespace OnTopReplica { namespace OnTopReplica {
class MessagePumpManager : IDisposable { class MessagePumpManager : IDisposable {
Dictionary<Type, IMessagePumpProcessor> _processors = new Dictionary<Type, IMessagePumpProcessor>(); Dictionary<Type, IMessagePumpProcessor> _processors = new Dictionary<Type, IMessagePumpProcessor>();
public MainForm Form { get; private set; } public MainForm Form { get; private set; }
private void Register(IMessagePumpProcessor processor, MainForm form) { private void Register(IMessagePumpProcessor processor, MainForm form) {
_processors[processor.GetType()] = processor; _processors[processor.GetType()] = processor;
processor.Initialize(form); processor.Initialize(form);
Log.Write("Registered message pump processor {0}", processor.GetType()); Log.Write("Registered message pump processor {0}", processor.GetType());
} }
/// <summary> /// <summary>
/// Instantiates all message pump processors and registers them on the main form. /// Instantiates all message pump processors and registers them on the main form.
/// </summary> /// </summary>
/// <param name="form"></param> /// <param name="form"></param>
public void Initialize(MainForm form) { public void Initialize(MainForm form) {
Form = form; Form = form;
//Register window shell hook //Register window shell hook
if (!HookMethods.RegisterShellHookWindow(form.Handle)) { if (!HookMethods.RegisterShellHookWindow(form.Handle)) {
Log.Write("Failed to register shell hook window"); Log.Write("Failed to register shell hook window");
} }
else { else {
Log.Write("Shell hook window registered successfully"); Log.Write("Shell hook window registered successfully");
} }
//Register message pump processors //Register message pump processors
Register(new WindowKeeper(), form); Register(new WindowKeeper(), form);
Register(new HotKeyManager(), form); Register(new HotKeyManager(), form);
Register(new GroupSwitchManager(), form); Register(new GroupSwitchManager(), form);
Register(new FlashCloner(), form); Register(new FlashCloner(), form);
} }
/// <summary> /// <summary>
/// Run the registered message pump processors. /// Run the registered message pump processors.
/// </summary> /// </summary>
/// <param name="msg">Message to process.</param> /// <param name="msg">Message to process.</param>
/// <returns>True if the message has been handled internally.</returns> /// <returns>True if the message has been handled internally.</returns>
public bool PumpMessage(ref Message msg) { public bool PumpMessage(ref Message msg) {
foreach (var processor in _processors.Values) { foreach (var processor in _processors.Values) {
if (processor.Process(ref msg)) if (processor.Process(ref msg))
return true; return true;
} }
return false; return false;
} }
/// <summary> /// <summary>
/// Get the instance of a registered message pump processor. /// Get the instance of a registered message pump processor.
/// Throws if instance not found. /// Throws if instance not found.
/// </summary> /// </summary>
public T Get<T>() { public T Get<T>() {
return (T)_processors[typeof(T)]; return (T)_processors[typeof(T)];
} }
#region IDisposable Members #region IDisposable Members
public void Dispose() { public void Dispose() {
if (!HookMethods.DeregisterShellHookWindow(Form.Handle)) { if (!HookMethods.DeregisterShellHookWindow(Form.Handle)) {
Log.Write("Failed to deregister shell hook window"); Log.Write("Failed to deregister shell hook window");
} }
else { else {
Log.Write("Deregistered shell hook window successfully"); Log.Write("Deregistered shell hook window successfully");
} }
foreach (var processor in _processors.Values) { foreach (var processor in _processors.Values) {
processor.Dispose(); processor.Dispose();
} }
_processors.Clear(); _processors.Clear();
} }
#endregion #endregion
} }
} }

View file

@ -1,39 +1,39 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
namespace OnTopReplica.MessagePumpProcessors { namespace OnTopReplica.MessagePumpProcessors {
abstract class BaseMessagePumpProcessor : IMessagePumpProcessor { abstract class BaseMessagePumpProcessor : IMessagePumpProcessor {
protected MainForm Form { get; private set; } protected MainForm Form { get; private set; }
#region IMessagePumpProcessor Members #region IMessagePumpProcessor Members
public virtual void Initialize(MainForm form) { public virtual void Initialize(MainForm form) {
Form = form; Form = form;
} }
public abstract bool Process(ref Message msg); public abstract bool Process(ref Message msg);
#endregion #endregion
protected abstract void Shutdown(); protected abstract void Shutdown();
bool _isDisposed = false; bool _isDisposed = false;
#region IDisposable Members #region IDisposable Members
public void Dispose() { public void Dispose() {
if (_isDisposed) if (_isDisposed)
return; return;
Shutdown(); Shutdown();
_isDisposed = true; _isDisposed = true;
} }
#endregion #endregion
} }
} }

View file

@ -1,35 +1,35 @@
using OnTopReplica.Native; using OnTopReplica.Native;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
namespace OnTopReplica.MessagePumpProcessors { namespace OnTopReplica.MessagePumpProcessors {
/// <summary> /// <summary>
/// Automatically clones windows that are flashing. /// Automatically clones windows that are flashing.
/// </summary> /// </summary>
class FlashCloner : BaseMessagePumpProcessor { class FlashCloner : BaseMessagePumpProcessor {
public override bool Process(ref System.Windows.Forms.Message msg) { public override bool Process(ref System.Windows.Forms.Message msg) {
if (false && if (false &&
msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) { msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) {
int hookCode = msg.WParam.ToInt32(); int hookCode = msg.WParam.ToInt32();
if (hookCode == HookMethods.HSHELL_FLASH) { if (hookCode == HookMethods.HSHELL_FLASH) {
IntPtr flashHandle = msg.LParam; IntPtr flashHandle = msg.LParam;
Form.SetThumbnail(new WindowHandle(flashHandle), null); Form.SetThumbnail(new WindowHandle(flashHandle), null);
} }
} }
return false; return false;
} }
protected override void Shutdown() { protected override void Shutdown() {
} }
} }
} }

View file

@ -1,133 +1,133 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Reflection; using System.Reflection;
using System.IO; using System.IO;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Native; using OnTopReplica.Native;
namespace OnTopReplica.MessagePumpProcessors { namespace OnTopReplica.MessagePumpProcessors {
class GroupSwitchManager : BaseMessagePumpProcessor { class GroupSwitchManager : BaseMessagePumpProcessor {
bool _active = false; bool _active = false;
List<WindowHandleWrapper> _lruHandles; List<WindowHandleWrapper> _lruHandles;
/// <summary> /// <summary>
/// Enables group switch mode. /// Enables group switch mode.
/// </summary> /// </summary>
/// <param name="handles">List of window handles to track.</param> /// <param name="handles">List of window handles to track.</param>
public void EnableGroupMode(IList<WindowHandle> handles) { public void EnableGroupMode(IList<WindowHandle> handles) {
if (handles == null || handles.Count == 0) if (handles == null || handles.Count == 0)
return; return;
//Okey dokey, will now track handles //Okey dokey, will now track handles
TrackHandles(handles); TrackHandles(handles);
_active = true; _active = true;
} }
/// <summary> /// <summary>
/// Initializes the LRU sorted list of window handles. /// Initializes the LRU sorted list of window handles.
/// </summary> /// </summary>
private void TrackHandles(IList<WindowHandle> handles) { private void TrackHandles(IList<WindowHandle> handles) {
_lruHandles = new List<WindowHandleWrapper>(handles.Count); _lruHandles = new List<WindowHandleWrapper>(handles.Count);
var now = DateTime.Now; var now = DateTime.Now;
foreach(var h in handles){ foreach(var h in handles){
_lruHandles.Add(new WindowHandleWrapper { _lruHandles.Add(new WindowHandleWrapper {
WindowHandle = h, WindowHandle = h,
LastTimeUsed = now LastTimeUsed = now
}); });
} }
} }
/// <summary> /// <summary>
/// Disables group switch mode. /// Disables group switch mode.
/// </summary> /// </summary>
public void Disable() { public void Disable() {
if (!_active) if (!_active)
return; return;
_lruHandles = null; _lruHandles = null;
_active = false; _active = false;
} }
/// <summary> /// <summary>
/// Processes the message pump. /// Processes the message pump.
/// </summary> /// </summary>
public override bool Process(ref Message msg) { public override bool Process(ref Message msg) {
if (_active && msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) { if (_active && msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) {
int hookCode = msg.WParam.ToInt32(); int hookCode = msg.WParam.ToInt32();
if (hookCode == HookMethods.HSHELL_WINDOWACTIVATED || if (hookCode == HookMethods.HSHELL_WINDOWACTIVATED ||
hookCode == HookMethods.HSHELL_RUDEAPPACTIVATED) { hookCode == HookMethods.HSHELL_RUDEAPPACTIVATED) {
IntPtr activeHandle = msg.LParam; IntPtr activeHandle = msg.LParam;
HandleForegroundWindowChange(activeHandle); HandleForegroundWindowChange(activeHandle);
} }
} }
return false; return false;
} }
private void HandleForegroundWindowChange(IntPtr activeWindow) { private void HandleForegroundWindowChange(IntPtr activeWindow) {
//Seek window in tracked handles //Seek window in tracked handles
WindowHandleWrapper activated = null; WindowHandleWrapper activated = null;
foreach (var i in _lruHandles) { foreach (var i in _lruHandles) {
if (i.WindowHandle.Handle == activeWindow) if (i.WindowHandle.Handle == activeWindow)
activated = i; activated = i;
} }
if (activated == null) { if (activated == null) {
//New foreground window is not tracked //New foreground window is not tracked
return; return;
} }
//Update tracked handle //Update tracked handle
activated.LastTimeUsed = DateTime.Now; activated.LastTimeUsed = DateTime.Now;
_lruHandles.Sort(new LruDateTimeComparer()); _lruHandles.Sort(new LruDateTimeComparer());
//Get least recently used //Get least recently used
var next = _lruHandles[0]; var next = _lruHandles[0];
Log.Write("Switched to tracked window: switching to {0} (last use: {1})", next.WindowHandle.Title, next.LastTimeUsed); Log.Write("Switched to tracked window: switching to {0} (last use: {1})", next.WindowHandle.Title, next.LastTimeUsed);
Form.SetThumbnail(next.WindowHandle, null); Form.SetThumbnail(next.WindowHandle, null);
} }
protected override void Shutdown() { protected override void Shutdown() {
Disable(); Disable();
} }
/// <summary> /// <summary>
/// Gets whether the group switch manager ia active. /// Gets whether the group switch manager ia active.
/// </summary> /// </summary>
public bool IsActive { public bool IsActive {
get { get {
return _active; return _active;
} }
} }
#region List sorting stuff #region List sorting stuff
class WindowHandleWrapper { class WindowHandleWrapper {
public WindowHandle WindowHandle { get; set; } public WindowHandle WindowHandle { get; set; }
public DateTime LastTimeUsed { get; set; } public DateTime LastTimeUsed { get; set; }
} }
class LruDateTimeComparer : IComparer<WindowHandleWrapper> { class LruDateTimeComparer : IComparer<WindowHandleWrapper> {
#region IComparer<WindowHandleWrapper> Members #region IComparer<WindowHandleWrapper> Members
public int Compare(WindowHandleWrapper x, WindowHandleWrapper y) { public int Compare(WindowHandleWrapper x, WindowHandleWrapper y) {
return x.LastTimeUsed.CompareTo(y.LastTimeUsed); return x.LastTimeUsed.CompareTo(y.LastTimeUsed);
} }
#endregion #endregion
} }
#endregion #endregion
} }
} }

View file

@ -1,167 +1,167 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Native; using OnTopReplica.Native;
using OnTopReplica.Properties; using OnTopReplica.Properties;
namespace OnTopReplica.MessagePumpProcessors { namespace OnTopReplica.MessagePumpProcessors {
/// <summary> /// <summary>
/// HotKey registration helper. /// HotKey registration helper.
/// </summary> /// </summary>
class HotKeyManager : BaseMessagePumpProcessor { class HotKeyManager : BaseMessagePumpProcessor {
public HotKeyManager() { public HotKeyManager() {
Enabled = true; Enabled = true;
} }
delegate void HotKeyHandler(); delegate void HotKeyHandler();
/// <summary> /// <summary>
/// Wraps hot key handler registration data. /// Wraps hot key handler registration data.
/// </summary> /// </summary>
private class HotKeyHandlerRegistration : IDisposable { private class HotKeyHandlerRegistration : IDisposable {
private HotKeyHandlerRegistration() { private HotKeyHandlerRegistration() {
} }
private HotKeyHandlerRegistration(IntPtr hwnd, int key, HotKeyHandler handler) { private HotKeyHandlerRegistration(IntPtr hwnd, int key, HotKeyHandler handler) {
if (hwnd == IntPtr.Zero) if (hwnd == IntPtr.Zero)
throw new ArgumentException(); throw new ArgumentException();
if (handler == null) if (handler == null)
throw new ArgumentNullException(); throw new ArgumentNullException();
_hwnd = hwnd; _hwnd = hwnd;
RegistrationKey = key; RegistrationKey = key;
Handler = handler; Handler = handler;
} }
static int _lastUsedKey = 0; static int _lastUsedKey = 0;
/// <summary> /// <summary>
/// Registers a new hotkey and returns a handle to the registration. /// Registers a new hotkey and returns a handle to the registration.
/// </summary> /// </summary>
/// <returns>Returns null on failure.</returns> /// <returns>Returns null on failure.</returns>
public static HotKeyHandlerRegistration Register(Form owner, int keyCode, int modifiers, HotKeyHandler handler) { public static HotKeyHandlerRegistration Register(Form owner, int keyCode, int modifiers, HotKeyHandler handler) {
var key = ++_lastUsedKey; var key = ++_lastUsedKey;
if (!HotKeyMethods.RegisterHotKey(owner.Handle, key, modifiers, keyCode)) { if (!HotKeyMethods.RegisterHotKey(owner.Handle, key, modifiers, keyCode)) {
Log.Write("Failed to create hotkey on key {0} with modifiers {1}", keyCode, modifiers); Log.Write("Failed to create hotkey on key {0} with modifiers {1}", keyCode, modifiers);
return null; return null;
} }
return new HotKeyHandlerRegistration(owner.Handle, key, handler); return new HotKeyHandlerRegistration(owner.Handle, key, handler);
} }
IntPtr _hwnd; IntPtr _hwnd;
public int RegistrationKey { get; private set; } public int RegistrationKey { get; private set; }
public HotKeyHandler Handler { get; private set; } public HotKeyHandler Handler { get; private set; }
public void Dispose() { public void Dispose() {
if (!HotKeyMethods.UnregisterHotKey(_hwnd, RegistrationKey)) { if (!HotKeyMethods.UnregisterHotKey(_hwnd, RegistrationKey)) {
Log.Write("Failed to unregister hotkey #{0}", RegistrationKey); Log.Write("Failed to unregister hotkey #{0}", RegistrationKey);
} }
} }
} }
Dictionary<int, HotKeyHandlerRegistration> _handlers = new Dictionary<int, HotKeyHandlerRegistration>(); Dictionary<int, HotKeyHandlerRegistration> _handlers = new Dictionary<int, HotKeyHandlerRegistration>();
public override void Initialize(MainForm form) { public override void Initialize(MainForm form) {
base.Initialize(form); base.Initialize(form);
RefreshHotkeys(); RefreshHotkeys();
} }
public override bool Process(ref Message msg) { public override bool Process(ref Message msg) {
if (Enabled && msg.Msg == HotKeyMethods.WM_HOTKEY) { if (Enabled && msg.Msg == HotKeyMethods.WM_HOTKEY) {
int keyId = msg.WParam.ToInt32(); int keyId = msg.WParam.ToInt32();
if (!_handlers.ContainsKey(keyId)) if (!_handlers.ContainsKey(keyId))
return false; return false;
_handlers[keyId].Handler.Invoke(); _handlers[keyId].Handler.Invoke();
} }
return false; return false;
} }
public bool Enabled { get; set; } public bool Enabled { get; set; }
/// <summary> /// <summary>
/// Refreshes registered hotkeys from Settings. /// Refreshes registered hotkeys from Settings.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Application settings contain hotkey registration strings that are used /// Application settings contain hotkey registration strings that are used
/// automatically by this registration process. /// automatically by this registration process.
/// </remarks> /// </remarks>
public void RefreshHotkeys() { public void RefreshHotkeys() {
ClearHandlers(); ClearHandlers();
RegisterHandler(Settings.Default.HotKeyCloneCurrent, HotKeyCloneHandler); RegisterHandler(Settings.Default.HotKeyCloneCurrent, HotKeyCloneHandler);
RegisterHandler(Settings.Default.HotKeyShowHide, HotKeyShowHideHandler); RegisterHandler(Settings.Default.HotKeyShowHide, HotKeyShowHideHandler);
} }
private void RegisterHandler(string spec, HotKeyHandler handler) { private void RegisterHandler(string spec, HotKeyHandler handler) {
if (string.IsNullOrEmpty(spec)) if (string.IsNullOrEmpty(spec))
return; //this can happen and is allowed => simply don't register return; //this can happen and is allowed => simply don't register
if (handler == null) if (handler == null)
throw new ArgumentNullException(); throw new ArgumentNullException();
int modifiers = 0, keyCode = 0; int modifiers = 0, keyCode = 0;
try { try {
HotKeyMethods.TranslateStringToKeyValues(spec, out modifiers, out keyCode); HotKeyMethods.TranslateStringToKeyValues(spec, out modifiers, out keyCode);
} }
catch (ArgumentException) { catch (ArgumentException) {
//TODO: swallowed exception //TODO: swallowed exception
return; return;
} }
var reg = HotKeyHandlerRegistration.Register(Form, keyCode, modifiers, handler); var reg = HotKeyHandlerRegistration.Register(Form, keyCode, modifiers, handler);
if(reg != null) if(reg != null)
_handlers.Add(reg.RegistrationKey, reg); _handlers.Add(reg.RegistrationKey, reg);
} }
private void ClearHandlers() { private void ClearHandlers() {
foreach (var hotkey in _handlers) { foreach (var hotkey in _handlers) {
hotkey.Value.Dispose(); hotkey.Value.Dispose();
} }
_handlers.Clear(); _handlers.Clear();
} }
protected override void Shutdown() { protected override void Shutdown() {
ClearHandlers(); ClearHandlers();
} }
#region Hotkey callbacks #region Hotkey callbacks
/// <summary> /// <summary>
/// Handles "show/hide" hotkey. Ensures the form is in restored state and switches /// Handles "show/hide" hotkey. Ensures the form is in restored state and switches
/// between shown and hidden states. /// between shown and hidden states.
/// </summary> /// </summary>
void HotKeyShowHideHandler() { void HotKeyShowHideHandler() {
Form.FullscreenManager.SwitchBack(); Form.FullscreenManager.SwitchBack();
if (!Program.Platform.IsHidden(Form)) { if (!Program.Platform.IsHidden(Form)) {
Program.Platform.HideForm(Form); Program.Platform.HideForm(Form);
} }
else { else {
Form.EnsureMainFormVisible(); Form.EnsureMainFormVisible();
} }
} }
/// <summary> /// <summary>
/// Handles the "clone current" hotkey. /// Handles the "clone current" hotkey.
/// </summary> /// </summary>
void HotKeyCloneHandler() { void HotKeyCloneHandler() {
var handle = Win32Helper.GetCurrentForegroundWindow(); var handle = Win32Helper.GetCurrentForegroundWindow();
if (handle.Handle == Form.Handle) if (handle.Handle == Form.Handle)
return; return;
Form.SetThumbnail(handle, null); Form.SetThumbnail(handle, null);
} }
#endregion #endregion
} }
} }

View file

@ -1,34 +1,34 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Native; using OnTopReplica.Native;
namespace OnTopReplica.MessagePumpProcessors { namespace OnTopReplica.MessagePumpProcessors {
#if DEBUG #if DEBUG
/// <summary> /// <summary>
/// Basic shell message interceptor to use for debugging. /// Basic shell message interceptor to use for debugging.
/// </summary> /// </summary>
class ShellInterceptProcessor : BaseMessagePumpProcessor { class ShellInterceptProcessor : BaseMessagePumpProcessor {
public override bool Process(ref Message msg) { public override bool Process(ref Message msg) {
if (msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) { if (msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) {
int hookCode = msg.WParam.ToInt32(); int hookCode = msg.WParam.ToInt32();
Log.Write("Hook msg #{0}: {1}", hookCode, msg.LParam); Log.Write("Hook msg #{0}: {1}", hookCode, msg.LParam);
} }
return false; return false;
} }
protected override void Shutdown() { protected override void Shutdown() {
} }
} }
#endif #endif
} }

View file

@ -1,40 +1,40 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Windows.Forms; using System.Windows.Forms;
using OnTopReplica.Native; using OnTopReplica.Native;
namespace OnTopReplica.MessagePumpProcessors { namespace OnTopReplica.MessagePumpProcessors {
/// <summary> /// <summary>
/// Listens for shell events and closes the thumbnail if a cloned window is destroyed. /// Listens for shell events and closes the thumbnail if a cloned window is destroyed.
/// </summary> /// </summary>
class WindowKeeper : BaseMessagePumpProcessor { class WindowKeeper : BaseMessagePumpProcessor {
public override bool Process(ref Message msg) { public override bool Process(ref Message msg) {
if (Form.CurrentThumbnailWindowHandle != null && if (Form.CurrentThumbnailWindowHandle != null &&
msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) { msg.Msg == HookMethods.WM_SHELLHOOKMESSAGE) {
int hookCode = msg.WParam.ToInt32(); int hookCode = msg.WParam.ToInt32();
if (hookCode == HookMethods.HSHELL_WINDOWDESTROYED) { if (hookCode == HookMethods.HSHELL_WINDOWDESTROYED) {
//Check whether the destroyed window is the one we were cloning //Check whether the destroyed window is the one we were cloning
IntPtr destroyedHandle = msg.LParam; IntPtr destroyedHandle = msg.LParam;
if (destroyedHandle == Form.CurrentThumbnailWindowHandle.Handle) { if (destroyedHandle == Form.CurrentThumbnailWindowHandle.Handle) {
//Disable group switch mode, since a window of the group has been destroyed //Disable group switch mode, since a window of the group has been destroyed
Form.MessagePumpManager.Get<GroupSwitchManager>().Disable(); Form.MessagePumpManager.Get<GroupSwitchManager>().Disable();
//Disable cloning //Disable cloning
Form.UnsetThumbnail(); Form.UnsetThumbnail();
} }
} }
} }
return false; return false;
} }
protected override void Shutdown() { protected override void Shutdown() {
} }
} }
} }

View file

@ -1,30 +1,30 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace OnTopReplica.Native { namespace OnTopReplica.Native {
public static class CommonControls { public static class CommonControls {
[DllImport("comctl32.dll", EntryPoint = "InitCommonControlsEx", CallingConvention = CallingConvention.StdCall)] [DllImport("comctl32.dll", EntryPoint = "InitCommonControlsEx", CallingConvention = CallingConvention.StdCall)]
static extern bool InitCommonControlsEx(ref INITCOMMONCONTROLSEX iccex); static extern bool InitCommonControlsEx(ref INITCOMMONCONTROLSEX iccex);
const int ICC_STANDARD_CLASSES = 0x00004000; const int ICC_STANDARD_CLASSES = 0x00004000;
const int ICC_WIN95_CLASSES = 0x000000FF; const int ICC_WIN95_CLASSES = 0x000000FF;
public static bool InitStandard() { public static bool InitStandard() {
INITCOMMONCONTROLSEX ex = new INITCOMMONCONTROLSEX(); INITCOMMONCONTROLSEX ex = new INITCOMMONCONTROLSEX();
ex.dwSize = 8; ex.dwSize = 8;
ex.dwICC = ICC_STANDARD_CLASSES | ICC_WIN95_CLASSES; ex.dwICC = ICC_STANDARD_CLASSES | ICC_WIN95_CLASSES;
return InitCommonControlsEx(ref ex); return InitCommonControlsEx(ref ex);
} }
} }
struct INITCOMMONCONTROLSEX { struct INITCOMMONCONTROLSEX {
public int dwSize; public int dwSize;
public int dwICC; public int dwICC;
} }
} }

View file

@ -1,37 +1,37 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
namespace OnTopReplica.Native { namespace OnTopReplica.Native {
/// <summary> /// <summary>
/// Common Win32 error handling methods. /// Common Win32 error handling methods.
/// </summary> /// </summary>
static class ErrorMethods { static class ErrorMethods {
[DllImport("kernel32.dll")] [DllImport("kernel32.dll")]
static extern uint FormatMessage(uint dwFlags, IntPtr lpSource, static extern uint FormatMessage(uint dwFlags, IntPtr lpSource,
int dwMessageId, uint dwLanguageId, [Out] StringBuilder lpBuffer, int dwMessageId, uint dwLanguageId, [Out] StringBuilder lpBuffer,
uint nSize, IntPtr Arguments); uint nSize, IntPtr Arguments);
/// <summary> /// <summary>
/// Gets a string representation of a Win32 error code. /// Gets a string representation of a Win32 error code.
/// </summary> /// </summary>
/// <param name="msgCode">ID of the Win32 error code.</param> /// <param name="msgCode">ID of the Win32 error code.</param>
/// <returns>String representation of the error.</returns> /// <returns>String representation of the error.</returns>
public static string GetErrorMessage(int msgCode) { public static string GetErrorMessage(int msgCode) {
var sb = new StringBuilder(300); var sb = new StringBuilder(300);
FormatMessage((uint)(0x00001000), IntPtr.Zero, msgCode, 0, sb, 299, IntPtr.Zero); FormatMessage((uint)(0x00001000), IntPtr.Zero, msgCode, 0, sb, 299, IntPtr.Zero);
return sb.ToString(); return sb.ToString();
} }
/// <summary> /// <summary>
/// Gets a string representation of the last Win32 error on this thread. /// Gets a string representation of the last Win32 error on this thread.
/// </summary> /// </summary>
public static string GetLastErrorMessage() { public static string GetLastErrorMessage() {
int errorCode = Marshal.GetLastWin32Error(); int errorCode = Marshal.GetLastWin32Error();
return GetErrorMessage(errorCode); return GetErrorMessage(errorCode);
} }
} }
} }

View file

@ -1,51 +1,51 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.IO; using System.IO;
namespace OnTopReplica.Native { namespace OnTopReplica.Native {
/// <summary> /// <summary>
/// Native methods for filesystem interop. /// Native methods for filesystem interop.
/// </summary> /// </summary>
static class FilesystemMethods { static class FilesystemMethods {
/// <summary> /// <summary>
/// Gets the path to the current user's download path. /// Gets the path to the current user's download path.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// Code taken from http://stackoverflow.com/questions/3795023/downloads-folder-not-special-enough /// Code taken from http://stackoverflow.com/questions/3795023/downloads-folder-not-special-enough
/// </remarks> /// </remarks>
public static string DownloadsPath { public static string DownloadsPath {
get { get {
string path = null; string path = null;
//Requires Vista or superior //Requires Vista or superior
if (Environment.OSVersion.Version.Major >= 6) { if (Environment.OSVersion.Version.Major >= 6) {
IntPtr pathPtr; IntPtr pathPtr;
Guid folderId = FolderDownloads; Guid folderId = FolderDownloads;
int hr = SHGetKnownFolderPath(ref folderId, 0, IntPtr.Zero, out pathPtr); int hr = SHGetKnownFolderPath(ref folderId, 0, IntPtr.Zero, out pathPtr);
if (hr == 0) { if (hr == 0) {
path = Marshal.PtrToStringUni(pathPtr); path = Marshal.PtrToStringUni(pathPtr);
Marshal.FreeCoTaskMem(pathPtr); Marshal.FreeCoTaskMem(pathPtr);
return path; return path;
} }
} }
//Fallback code //Fallback code
path = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Personal)); path = Path.GetDirectoryName(Environment.GetFolderPath(Environment.SpecialFolder.Personal));
path = Path.Combine(path, "Downloads"); path = Path.Combine(path, "Downloads");
return path; return path;
} }
} }
static readonly Guid FolderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B"); static readonly Guid FolderDownloads = new Guid("374DE290-123F-4565-9164-39C4925E467B");
[DllImport("shell32.dll", CharSet = CharSet.Auto)] [DllImport("shell32.dll", CharSet = CharSet.Auto)]
private static extern int SHGetKnownFolderPath(ref Guid id, int flags, IntPtr token, out IntPtr path); private static extern int SHGetKnownFolderPath(ref Guid id, int flags, IntPtr token, out IntPtr path);
} }
} }

View file

@ -1,14 +1,14 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text; using System.Text;
namespace OnTopReplica.Native { namespace OnTopReplica.Native {
/// <summary> /// <summary>
/// Native Win32 Hit Testing codes. /// Native Win32 Hit Testing codes.
/// </summary> /// </summary>
static class HT { static class HT {
public const int TRANSPARENT = -1; public const int TRANSPARENT = -1;
public const int CLIENT = 1; public const int CLIENT = 1;
public const int CAPTION = 2; public const int CAPTION = 2;
} }
} }

View file

@ -1,54 +1,54 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text; using System.Text;
namespace OnTopReplica.Native { namespace OnTopReplica.Native {
/// <summary> /// <summary>
/// Helpers for interop with native Windows hooks. /// Helpers for interop with native Windows hooks.
/// </summary> /// </summary>
static class HookMethods { static class HookMethods {
static HookMethods() { static HookMethods() {
WM_SHELLHOOKMESSAGE = RegisterWindowMessage("SHELLHOOK"); WM_SHELLHOOKMESSAGE = RegisterWindowMessage("SHELLHOOK");
if (WM_SHELLHOOKMESSAGE == 0) { if (WM_SHELLHOOKMESSAGE == 0) {
Log.Write("Failed to register SHELLHOOK window message"); Log.Write("Failed to register SHELLHOOK window message");
} }
} }
public static int WM_SHELLHOOKMESSAGE { public static int WM_SHELLHOOKMESSAGE {
get; get;
private set; private set;
} }
const int HSHELL_HIGHBIT = 0x8000; const int HSHELL_HIGHBIT = 0x8000;
public const int HSHELL_WINDOWCREATED = 1; public const int HSHELL_WINDOWCREATED = 1;
public const int HSHELL_WINDOWDESTROYED = 2; public const int HSHELL_WINDOWDESTROYED = 2;
public const int HSHELL_WINDOWACTIVATED = 4; public const int HSHELL_WINDOWACTIVATED = 4;
public const int HSHELL_REDRAW = 6; public const int HSHELL_REDRAW = 6;
public const int HSHELL_RUDEAPPACTIVATED = (HSHELL_WINDOWACTIVATED | HSHELL_HIGHBIT); public const int HSHELL_RUDEAPPACTIVATED = (HSHELL_WINDOWACTIVATED | HSHELL_HIGHBIT);
public const int HSHELL_FLASH = (HSHELL_REDRAW | HSHELL_HIGHBIT); public const int HSHELL_FLASH = (HSHELL_REDRAW | HSHELL_HIGHBIT);
/// <summary> /// <summary>
/// Registers the WM_ID for a window message. /// Registers the WM_ID for a window message.
/// </summary> /// </summary>
/// <param name="wndMessageName">Name of the window message.</param> /// <param name="wndMessageName">Name of the window message.</param>
[DllImport("User32.dll")] [DllImport("User32.dll")]
public static extern int RegisterWindowMessage(string wndMessageName); public static extern int RegisterWindowMessage(string wndMessageName);
/// <summary> /// <summary>
/// Registers a window as a shell hook window. /// Registers a window as a shell hook window.
/// </summary> /// </summary>
[DllImport("User32.dll")] [DllImport("User32.dll")]
public static extern bool RegisterShellHookWindow(IntPtr hwnd); public static extern bool RegisterShellHookWindow(IntPtr hwnd);
/// <summary> /// <summary>
/// Deregisters a window as a shell hook window. /// Deregisters a window as a shell hook window.
/// </summary> /// </summary>
[DllImport("User32.dll")] [DllImport("User32.dll")]
public static extern bool DeregisterShellHookWindow(IntPtr hwnd); public static extern bool DeregisterShellHookWindow(IntPtr hwnd);
} }
} }

Some files were not shown because too many files have changed in this diff Show more