mirror of
https://github.com/Maassoft/ColorControl.git
synced 2026-10-19 15:20:15 -05:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8910a3b64 | ||
|
|
b2e7c529a0 | ||
|
|
977060e927 | ||
|
|
f609471fd2 | ||
|
|
a1a94d27db | ||
|
|
e12faaba27 | ||
|
|
6f5f7c4dd3 | ||
|
|
e1800b8d50 | ||
|
|
7779533c1e | ||
|
|
74cefc00f7 | ||
|
|
a8d33b6a30 | ||
|
|
f83869da04 | ||
|
|
815710c081 | ||
|
|
805c516371 | ||
|
|
b85d929890 | ||
|
|
dd9ce932fc | ||
|
|
3667243fc7 | ||
|
|
92f4ab8ef5 | ||
|
|
90ca095954 | ||
|
|
fa63d8dc4f | ||
|
|
fc134b146a | ||
|
|
3abf106496 | ||
|
|
a17534abcb | ||
|
|
4614886954 | ||
|
|
26a91dc7e9 | ||
|
|
cac5180c76 | ||
|
|
0c877623c0 | ||
|
|
a33543acd5 | ||
|
|
7f6175f8ef | ||
|
|
fd51bcca99 | ||
|
|
5268e6679e | ||
|
|
91fd44d698 | ||
|
|
48b13b1c64 | ||
|
|
d2aacbb8e0 | ||
|
|
04d52d6062 | ||
|
|
13420d2855 | ||
|
|
43a4660cc5 | ||
|
|
8683cd5be0 | ||
|
|
038a70cc81 |
No files matched your search
+2
-1
@@ -337,4 +337,5 @@ ASALocalRun/
|
||||
.localhistory/
|
||||
|
||||
# BeatPulse healthcheck temp database
|
||||
healthchecksdb
|
||||
healthchecksdb
|
||||
*.clef
|
||||
+5
-5
@@ -1,9 +1,9 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30128.74
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.0.32014.148
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ColorControl", "ColorControl\ColorControl.csproj", "{A6005D08-70F0-44CB-A384-9219EBA84F21}"
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ColorControl", "ColorControl\ColorControl.csproj", "{A6005D08-70F0-44CB-A384-9219EBA84F21}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
@@ -15,8 +15,8 @@ Global
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Debug|x64.Build.0 = Debug|x64
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Debug|x64.ActiveCfg = Debug|Any CPU
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Debug|x64.Build.0 = Debug|Any CPU
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{A6005D08-70F0-44CB-A384-9219EBA84F21}.Release|x64.ActiveCfg = Release|x64
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
{"Build":"0.3.261602\u002Befb3cc30a24e699e6e4337f263a2b9478f04f618","CurrentProject":"ColorControl.csproj","EntryPoints":["ColorControl.csproj"],"Properties":{}}
|
||||
+90
-228
@@ -23,12 +23,10 @@
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Diagnostics;
|
||||
using System.Threading;
|
||||
using FARPROC = System.IntPtr;
|
||||
using HMODULE = System.IntPtr;
|
||||
using ADL_CONTEXT_HANDLE = System.IntPtr;
|
||||
|
||||
#endregion Using
|
||||
|
||||
@@ -36,52 +34,6 @@ using HMODULE = System.IntPtr;
|
||||
|
||||
namespace ATI.ADL
|
||||
{
|
||||
#region Export Delegates
|
||||
/// <summary> ADL Memory allocation function allows ADL to callback for memory allocation</summary>
|
||||
/// <param name="size">input size</param>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate IntPtr ADL_Main_Memory_Alloc (int size);
|
||||
|
||||
// ///// <summary> ADL Create Function to create ADL Data</summary>
|
||||
/// <param name="callback">Call back functin pointer which is ised to allocate memeory </param>
|
||||
/// <param name="enumConnectedAdapters">If it is 1, then ADL will only retuen the physical exist adapters </param>
|
||||
///// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Main_Control_Create(ADL_Main_Memory_Alloc callback, int enumConnectedAdapters);
|
||||
|
||||
/// <summary> ADL Destroy Function to free up ADL Data</summary>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Main_Control_Destroy ();
|
||||
|
||||
/// <summary> ADL Function to get the number of adapters</summary>
|
||||
/// <param name="numAdapters">return number of adapters</param>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Adapter_NumberOfAdapters_Get (ref int numAdapters);
|
||||
|
||||
/// <summary> ADL Function to get the GPU adapter information</summary>
|
||||
/// <param name="info">return GPU adapter information</param>
|
||||
/// <param name="inputSize">the size of the GPU adapter struct</param>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Adapter_AdapterInfo_Get (IntPtr info, int inputSize);
|
||||
|
||||
/// <summary> Function to determine if the adapter is active or not.</summary>
|
||||
/// <remarks>The function is used to check if the adapter associated with iAdapterIndex is active</remarks>
|
||||
/// <param name="adapterIndex"> Adapter Index.</param>
|
||||
/// <param name="status"> Status of the adapter. True: Active; False: Dsiabled</param>
|
||||
/// <returns>Non zero is successfull</returns>
|
||||
internal delegate int ADL_Adapter_Active_Get(int adapterIndex, ref int status);
|
||||
|
||||
/// <summary>Get display information based on adapter index</summary>
|
||||
/// <param name="adapterIndex">Adapter Index</param>
|
||||
/// <param name="numDisplays">return the total number of supported displays</param>
|
||||
/// <param name="displayInfoArray">return ADLDisplayInfo Array for supported displays' information</param>
|
||||
/// <param name="forceDetect">force detect or not</param>
|
||||
/// <returns>return ADL Error Code</returns>
|
||||
internal delegate int ADL_Display_DisplayInfo_Get(int adapterIndex, ref int numDisplays, out IntPtr displayInfoArray, int forceDetect);
|
||||
|
||||
internal delegate int ADL_Display_Size_Get(int adapterIndex, int displayIndex, ref int lpWidth, ref int lpHeight, ref int lpDefaultWidth, ref int lpDefaultHeight, ref int lpMinWidth, ref int lpMinHeight, ref int lpMaxWidth, ref int lpMaxHeight, ref int lpStepWidth, ref int lpStepHeight);
|
||||
|
||||
#endregion Export Delegates
|
||||
|
||||
#region Export Struct
|
||||
|
||||
#region ADLAdapterInfo
|
||||
@@ -207,10 +159,74 @@ namespace ATI.ADL
|
||||
/// <summary> Maximum number of GL-Sync ports on the GL-Sync module </summary>
|
||||
internal const int ADL_MAX_GLSYNC_PORT_LEDS = 8;
|
||||
/// <summary> Maximum number of ADLMOdes for the adapter </summary>
|
||||
internal const int ADL_MAX_NUM_DISPLAYMODES = 1024;
|
||||
internal const int ADL_MAX_NUM_DISPLAYMODES = 1024;
|
||||
|
||||
internal static Dictionary<Type, object> ADLDelegates = new Dictionary<Type, object>();
|
||||
|
||||
#endregion Internal Constant
|
||||
|
||||
#region Export Delegates
|
||||
/// <summary> ADL Memory allocation function allows ADL to callback for memory allocation</summary>
|
||||
/// <param name="size">input size</param>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate IntPtr ADL_Main_Memory_Alloc(int size);
|
||||
|
||||
// ///// <summary> ADL Create Function to create ADL Data</summary>
|
||||
/// <param name="callback">Call back functin pointer which is ised to allocate memeory </param>
|
||||
/// <param name="enumConnectedAdapters">If it is 1, then ADL will only retuen the physical exist adapters </param>
|
||||
///// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Main_Control_Create(ADL_Main_Memory_Alloc callback, int enumConnectedAdapters);
|
||||
|
||||
internal delegate int ADL2_Main_Control_Create(ADL_Main_Memory_Alloc callback, int enumConnectedAdapters, ref ADL_CONTEXT_HANDLE context);
|
||||
|
||||
/// <summary> ADL Destroy Function to free up ADL Data</summary>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Main_Control_Destroy();
|
||||
|
||||
internal delegate int ADL2_Main_Control_Destroy(ADL_CONTEXT_HANDLE context);
|
||||
|
||||
/// <summary> ADL Function to get the number of adapters</summary>
|
||||
/// <param name="numAdapters">return number of adapters</param>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Adapter_NumberOfAdapters_Get(ref int numAdapters);
|
||||
|
||||
/// <summary> ADL Function to get the GPU adapter information</summary>
|
||||
/// <param name="info">return GPU adapter information</param>
|
||||
/// <param name="inputSize">the size of the GPU adapter struct</param>
|
||||
/// <returns> retrun ADL Error Code</returns>
|
||||
internal delegate int ADL_Adapter_AdapterInfo_Get(IntPtr info, int inputSize);
|
||||
|
||||
/// <summary> Function to determine if the adapter is active or not.</summary>
|
||||
/// <remarks>The function is used to check if the adapter associated with iAdapterIndex is active</remarks>
|
||||
/// <param name="adapterIndex"> Adapter Index.</param>
|
||||
/// <param name="status"> Status of the adapter. True: Active; False: Dsiabled</param>
|
||||
/// <returns>Non zero is successfull</returns>
|
||||
internal delegate int ADL_Adapter_Active_Get(int adapterIndex, ref int status);
|
||||
|
||||
/// <summary>Get display information based on adapter index</summary>
|
||||
/// <param name="adapterIndex">Adapter Index</param>
|
||||
/// <param name="numDisplays">return the total number of supported displays</param>
|
||||
/// <param name="displayInfoArray">return ADLDisplayInfo Array for supported displays' information</param>
|
||||
/// <param name="forceDetect">force detect or not</param>
|
||||
/// <returns>return ADL Error Code</returns>
|
||||
internal delegate int ADL_Display_DisplayInfo_Get(int adapterIndex, ref int numDisplays, out IntPtr displayInfoArray, int forceDetect);
|
||||
|
||||
internal delegate int ADL_Display_Size_Get(int adapterIndex, int displayIndex, ref int lpWidth, ref int lpHeight, ref int lpDefaultWidth, ref int lpDefaultHeight, ref int lpMinWidth, ref int lpMinHeight, ref int lpMaxWidth, ref int lpMaxHeight, ref int lpStepWidth, ref int lpStepHeight);
|
||||
|
||||
internal delegate int ADL_Display_PixelFormat_Get(int adapterIndex, int displayIndex, ref int pixelFormat);
|
||||
internal delegate int ADL_Display_PixelFormat_Set(int adapterIndex, int displayIndex, int pixelFormat);
|
||||
|
||||
internal delegate int ADL_Display_ColorDepth_Get(int adapterIndex, int displayIndex, ref int colorDepth);
|
||||
internal delegate int ADL_Display_ColorDepth_Set(int adapterIndex, int displayIndex, int colorDepth);
|
||||
|
||||
internal delegate int ADL_Display_DitherState_Get(int adapterIndex, int displayIndex, ref int ditherState);
|
||||
internal delegate int ADL_Display_DitherState_Set(int adapterIndex, int displayIndex, int ditherState);
|
||||
|
||||
internal delegate int ADL2_Display_HDRState_Get(ADL_CONTEXT_HANDLE context, int adapterIndex, ADLDisplayID displayID, ref int support, ref int enable);
|
||||
internal delegate int ADL2_Display_HDRState_Set(ADL_CONTEXT_HANDLE context, int adapterIndex, ADLDisplayID displayID, int enable);
|
||||
|
||||
#endregion Export Delegates
|
||||
|
||||
#region Class ADLImport
|
||||
/// <summary> ADLImport class</summary>
|
||||
private static class ADLImport
|
||||
@@ -227,31 +243,10 @@ namespace ATI.ADL
|
||||
internal static extern HMODULE GetModuleHandle (string moduleName);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Main_Control_Create (ADL_Main_Memory_Alloc callback, int enumConnectedAdapters);
|
||||
internal static extern int ADL_Main_Control_IsFunctionValid(HMODULE module, string procName);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Main_Control_Destroy ();
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Main_Control_IsFunctionValid (HMODULE module, string procName);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern FARPROC ADL_Main_Control_GetProcAddress (HMODULE module, string procName);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Adapter_NumberOfAdapters_Get (ref int numAdapters);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Adapter_AdapterInfo_Get (IntPtr info, int inputSize);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Adapter_Active_Get(int adapterIndex, ref int status);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Display_DisplayInfo_Get(int adapterIndex, ref int numDisplays, out IntPtr displayInfoArray, int forceDetect);
|
||||
|
||||
[DllImport(Atiadlxx_FileName)]
|
||||
internal static extern int ADL_Display_Size_Get(int iAdapterIndex, int iDisplayIndex, ref int lpWidth, ref int lpHeight, ref int lpDefaultWidth, ref int lpDefaultHeight, ref int lpMinWidth, ref int lpMinHeight, ref int lpMaxWidth, ref int lpMaxHeight, ref int lpStepWidth, ref int lpStepHeight);
|
||||
internal static extern FARPROC ADL_Main_Control_GetProcAddress(HMODULE module, string procName);
|
||||
|
||||
#endregion DLLImport
|
||||
}
|
||||
@@ -291,9 +286,13 @@ namespace ATI.ADL
|
||||
/// <summary> Destructor to force calling ADL Destroy function before free up the ADL library</summary>
|
||||
~ADLCheckLibrary ()
|
||||
{
|
||||
if (System.IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
|
||||
if (IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
|
||||
{
|
||||
ADLImport.ADL_Main_Control_Destroy();
|
||||
var del = ADL.GetDelegate<ADL.ADL_Main_Control_Destroy>();
|
||||
if (del != null)
|
||||
{
|
||||
del();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion Destructor
|
||||
@@ -304,8 +303,8 @@ namespace ATI.ADL
|
||||
/// <returns>return true, if function exists</returns>
|
||||
internal static bool IsFunctionValid (string functionName)
|
||||
{
|
||||
bool result = false;
|
||||
if (System.IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
|
||||
var result = false;
|
||||
if (IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
|
||||
{
|
||||
if (1 == ADLImport.ADL_Main_Control_IsFunctionValid(ADLCheckLibrary_.ADLLibrary, functionName))
|
||||
{
|
||||
@@ -322,8 +321,8 @@ namespace ATI.ADL
|
||||
/// <returns>return function pointer, if function exists</returns>
|
||||
internal static FARPROC GetProcAddress (string functionName)
|
||||
{
|
||||
FARPROC result = System.IntPtr.Zero;
|
||||
if (System.IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
|
||||
var result = IntPtr.Zero;
|
||||
if (IntPtr.Zero != ADLCheckLibrary_.ADLLibrary)
|
||||
{
|
||||
result = ADLImport.ADL_Main_Control_GetProcAddress(ADLCheckLibrary_.ADLLibrary, functionName);
|
||||
}
|
||||
@@ -337,7 +336,7 @@ namespace ATI.ADL
|
||||
|
||||
#region ADL_Main_Memory_Alloc
|
||||
/// <summary> Build in memory allocation function</summary>
|
||||
internal static ADL_Main_Memory_Alloc ADL_Main_Memory_Alloc = ADL_Main_Memory_Alloc_;
|
||||
internal static ADL_Main_Memory_Alloc ADL_Main_Memory_Alloc_Func = ADL_Main_Memory_Alloc_;
|
||||
/// <summary> Build in memory allocation function</summary>
|
||||
/// <param name="size">input size</param>
|
||||
/// <returns>return the memory buffer</returns>
|
||||
@@ -360,166 +359,29 @@ namespace ATI.ADL
|
||||
}
|
||||
#endregion ADL_Main_Memory_Free
|
||||
|
||||
#region ADL_Main_Control_Create
|
||||
/// <summary> ADL_Main_Control_Create Delegates</summary>
|
||||
internal static ADL_Main_Control_Create ADL_Main_Control_Create
|
||||
public static T GetDelegate<T>() where T : class
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!ADL_Main_Control_Create_Check && null == ADL_Main_Control_Create_)
|
||||
{
|
||||
ADL_Main_Control_Create_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Main_Control_Create"))
|
||||
{
|
||||
ADL_Main_Control_Create_ = ADLImport.ADL_Main_Control_Create;
|
||||
}
|
||||
}
|
||||
return ADL_Main_Control_Create_;
|
||||
}
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Main_Control_Create ADL_Main_Control_Create_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Main_Control_Create_Check = false;
|
||||
#endregion ADL_Main_Control_Create
|
||||
var type = typeof(T);
|
||||
|
||||
#region ADL_Main_Control_Destroy
|
||||
/// <summary> ADL_Main_Control_Destroy Delegates</summary>
|
||||
internal static ADL_Main_Control_Destroy ADL_Main_Control_Destroy
|
||||
{
|
||||
get
|
||||
lock (ADLDelegates)
|
||||
{
|
||||
if (!ADL_Main_Control_Destroy_Check && null == ADL_Main_Control_Destroy_)
|
||||
if (ADLDelegates.ContainsKey(type))
|
||||
{
|
||||
ADL_Main_Control_Destroy_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Main_Control_Destroy"))
|
||||
{
|
||||
ADL_Main_Control_Destroy_ = ADLImport.ADL_Main_Control_Destroy;
|
||||
}
|
||||
return ADLDelegates[type] as T;
|
||||
}
|
||||
return ADL_Main_Control_Destroy_;
|
||||
}
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Main_Control_Destroy ADL_Main_Control_Destroy_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Main_Control_Destroy_Check = false;
|
||||
#endregion ADL_Main_Control_Destroy
|
||||
|
||||
#region ADL_Adapter_NumberOfAdapters_Get
|
||||
/// <summary> ADL_Adapter_NumberOfAdapters_Get Delegates</summary>
|
||||
internal static ADL_Adapter_NumberOfAdapters_Get ADL_Adapter_NumberOfAdapters_Get
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!ADL_Adapter_NumberOfAdapters_Get_Check && null == ADL_Adapter_NumberOfAdapters_Get_)
|
||||
var ptr = ADLCheckLibrary.GetProcAddress(type.Name);
|
||||
if (ptr != FARPROC.Zero)
|
||||
{
|
||||
ADL_Adapter_NumberOfAdapters_Get_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Adapter_NumberOfAdapters_Get"))
|
||||
{
|
||||
ADL_Adapter_NumberOfAdapters_Get_ = ADLImport.ADL_Adapter_NumberOfAdapters_Get;
|
||||
}
|
||||
}
|
||||
return ADL_Adapter_NumberOfAdapters_Get_;
|
||||
}
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Adapter_NumberOfAdapters_Get ADL_Adapter_NumberOfAdapters_Get_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Adapter_NumberOfAdapters_Get_Check = false;
|
||||
#endregion ADL_Adapter_NumberOfAdapters_Get
|
||||
var delegateValue = Marshal.GetDelegateForFunctionPointer(ptr, type);
|
||||
ADLDelegates.Add(type, delegateValue);
|
||||
|
||||
#region ADL_Adapter_AdapterInfo_Get
|
||||
/// <summary> ADL_Adapter_AdapterInfo_Get Delegates</summary>
|
||||
internal static ADL_Adapter_AdapterInfo_Get ADL_Adapter_AdapterInfo_Get
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!ADL_Adapter_AdapterInfo_Get_Check && null == ADL_Adapter_AdapterInfo_Get_)
|
||||
{
|
||||
ADL_Adapter_AdapterInfo_Get_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Adapter_AdapterInfo_Get"))
|
||||
{
|
||||
ADL_Adapter_AdapterInfo_Get_ = ADLImport.ADL_Adapter_AdapterInfo_Get;
|
||||
}
|
||||
return delegateValue as T;
|
||||
}
|
||||
return ADL_Adapter_AdapterInfo_Get_;
|
||||
}
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Adapter_AdapterInfo_Get ADL_Adapter_AdapterInfo_Get_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Adapter_AdapterInfo_Get_Check = false;
|
||||
#endregion ADL_Adapter_AdapterInfo_Get
|
||||
|
||||
#region ADL_Adapter_Active_Get
|
||||
/// <summary> ADL_Adapter_Active_Get Delegates</summary>
|
||||
internal static ADL_Adapter_Active_Get ADL_Adapter_Active_Get
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!ADL_Adapter_Active_Get_Check && null == ADL_Adapter_Active_Get_)
|
||||
{
|
||||
ADL_Adapter_Active_Get_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Adapter_Active_Get"))
|
||||
{
|
||||
ADL_Adapter_Active_Get_ = ADLImport.ADL_Adapter_Active_Get;
|
||||
}
|
||||
}
|
||||
return ADL_Adapter_Active_Get_;
|
||||
}
|
||||
throw new InvalidProgramException("ADL-function not supported");
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Adapter_Active_Get ADL_Adapter_Active_Get_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Adapter_Active_Get_Check = false;
|
||||
#endregion ADL_Adapter_Active_Get
|
||||
|
||||
#region ADL_Display_DisplayInfo_Get
|
||||
/// <summary> ADL_Display_DisplayInfo_Get Delegates</summary>
|
||||
internal static ADL_Display_DisplayInfo_Get ADL_Display_DisplayInfo_Get
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!ADL_Display_DisplayInfo_Get_Check && null == ADL_Display_DisplayInfo_Get_)
|
||||
{
|
||||
ADL_Display_DisplayInfo_Get_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Display_DisplayInfo_Get"))
|
||||
{
|
||||
ADL_Display_DisplayInfo_Get_ = ADLImport.ADL_Display_DisplayInfo_Get;
|
||||
}
|
||||
}
|
||||
return ADL_Display_DisplayInfo_Get_;
|
||||
}
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Display_DisplayInfo_Get ADL_Display_DisplayInfo_Get_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Display_DisplayInfo_Get_Check = false;
|
||||
#endregion ADL_Display_DisplayInfo_Get
|
||||
|
||||
#region ADL_Display_Size_Get
|
||||
/// <summary> ADL_Display_Size_Get Delegates</summary>
|
||||
internal static ADL_Display_Size_Get ADL_Display_Size_Get
|
||||
{
|
||||
get
|
||||
{
|
||||
if (!ADL_Display_Size_Get_Check && null == ADL_Display_Size_Get)
|
||||
{
|
||||
ADL_Display_Size_Get_Check = true;
|
||||
if (ADLCheckLibrary.IsFunctionValid("ADL_Display_Size_Get"))
|
||||
{
|
||||
ADL_Display_Size_Get_ = ADLImport.ADL_Display_Size_Get;
|
||||
}
|
||||
}
|
||||
return ADL_Display_Size_Get_;
|
||||
}
|
||||
}
|
||||
/// <summary> Private Delegate</summary>
|
||||
private static ADL_Display_Size_Get ADL_Display_Size_Get_ = null;
|
||||
/// <summary> check flag to indicate the delegate has been checked</summary>
|
||||
private static bool ADL_Display_Size_Get_Check = false;
|
||||
#endregion ADL_Display_Size_Get
|
||||
|
||||
#endregion Export Functions
|
||||
}
|
||||
|
||||
+281
-53
@@ -3,28 +3,111 @@ using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
using ADL_CONTEXT_HANDLE = System.IntPtr;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
enum ADLPixelFormat
|
||||
{
|
||||
UNKNOWN = 0,
|
||||
RGB_FULL_RANGE = 1,
|
||||
YCRCB444 = 2,
|
||||
YCRCB422 = 3,
|
||||
RGB_LIMITED_RANGE = 4,
|
||||
YCRCB420 = 8
|
||||
}
|
||||
|
||||
enum ADLColorDepth
|
||||
{
|
||||
UNKNOWN = 0,
|
||||
BPC6 = 1,
|
||||
BPC8 = 2,
|
||||
BPC10 = 3,
|
||||
BPC12 = 4,
|
||||
BPC14 = 5,
|
||||
BPC16 = 6
|
||||
}
|
||||
|
||||
enum ADLDitherState
|
||||
{
|
||||
DISABLED = 0,
|
||||
DRIVER_DEFAULT = 1,
|
||||
FM6 = 2,
|
||||
FM8 = 3,
|
||||
FM10 = 4,
|
||||
DITH6 = 5,
|
||||
DITH8 = 6,
|
||||
DITH10 = 7,
|
||||
DITH6_NO_FRAME_RAND = 8,
|
||||
DITH8_NO_FRAME_RAND = 9,
|
||||
DITH10_NO_FRAME_RAND = 10,
|
||||
TRUN6 = 11,
|
||||
TRUN8 = 12,
|
||||
TRUN10 = 13,
|
||||
TRUN8_DITH8 = 14,
|
||||
TRUN10_DUTH6 = 15,
|
||||
TRUN10_FM8 = 16,
|
||||
TRUN10_FM6 = 17,
|
||||
TRUN10_DITH8_FM6 = 18,
|
||||
DITH10_FM8 = 19,
|
||||
DITH10_FM6 = 20,
|
||||
TRUN8_DITH6 = 21,
|
||||
TRUN8_FM6 = 22,
|
||||
DITH8_FM6 = 23
|
||||
}
|
||||
|
||||
class ADLWrapper
|
||||
{
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
private static ADL_CONTEXT_HANDLE context = IntPtr.Zero;
|
||||
|
||||
public static bool Initialize()
|
||||
{
|
||||
int ADLRet = -1;
|
||||
|
||||
if (null != ADL.ADL_Main_Control_Create)
|
||||
//Logger.Debug("Initialize");
|
||||
|
||||
var del = ADL.GetDelegate<ADL.ADL_Main_Control_Create>();
|
||||
|
||||
if (del != null)
|
||||
{
|
||||
// Second parameter is 1: Get only the present adapters
|
||||
ADLRet = ADL.ADL_Main_Control_Create(ADL.ADL_Main_Memory_Alloc, 1);
|
||||
ADLRet = del(ADL.ADL_Main_Memory_Alloc_Func, 1);
|
||||
CheckError(ADLRet, nameof(ADL.ADL_Main_Control_Create));
|
||||
}
|
||||
|
||||
var del2 = ADL.GetDelegate<ADL.ADL2_Main_Control_Create>();
|
||||
|
||||
if (del2 != null)
|
||||
{
|
||||
// Second parameter is 1: Get only the present adapters
|
||||
ADLRet = del2(ADL.ADL_Main_Memory_Alloc_Func, 1, ref context);
|
||||
CheckError(ADLRet, nameof(ADL.ADL2_Main_Control_Create));
|
||||
}
|
||||
|
||||
return (ADL.ADL_SUCCESS == ADLRet);
|
||||
}
|
||||
|
||||
public static void Uninitialze()
|
||||
{
|
||||
if (null != ADL.ADL_Main_Control_Destroy)
|
||||
if (!ADL.ADLDelegates.Any())
|
||||
{
|
||||
ADL.ADL_Main_Control_Destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
var del = ADL.GetDelegate<ADL.ADL_Main_Control_Destroy>();
|
||||
|
||||
if (null != del)
|
||||
{
|
||||
del();
|
||||
}
|
||||
|
||||
var del2 = ADL.GetDelegate<ADL.ADL2_Main_Control_Destroy>();
|
||||
|
||||
if (null != del2 && context != IntPtr.Zero)
|
||||
{
|
||||
del2(context);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,11 +116,13 @@ namespace ColorControl
|
||||
int ADLRet = -1;
|
||||
int NumberOfAdapters = 0;
|
||||
|
||||
if (null != ADL.ADL_Adapter_NumberOfAdapters_Get)
|
||||
var delNumberOfAdapters = ADL.GetDelegate<ADL.ADL_Adapter_NumberOfAdapters_Get>();
|
||||
|
||||
if (null != delNumberOfAdapters)
|
||||
{
|
||||
ADL.ADL_Adapter_NumberOfAdapters_Get(ref NumberOfAdapters);
|
||||
delNumberOfAdapters(ref NumberOfAdapters);
|
||||
}
|
||||
Console.WriteLine("Number Of Adapters: " + NumberOfAdapters.ToString() + "\n");
|
||||
Logger.Debug("Number Of Adapters: " + NumberOfAdapters.ToString() + "\n");
|
||||
|
||||
if (NumberOfAdapters > 0)
|
||||
{
|
||||
@@ -45,37 +130,38 @@ namespace ColorControl
|
||||
ADLAdapterInfoArray OSAdapterInfoData;
|
||||
OSAdapterInfoData = new ADLAdapterInfoArray();
|
||||
|
||||
if (null != ADL.ADL_Adapter_AdapterInfo_Get)
|
||||
var delAdapterInfo = ADL.GetDelegate<ADL.ADL_Adapter_AdapterInfo_Get>();
|
||||
|
||||
if (null != delAdapterInfo)
|
||||
{
|
||||
IntPtr AdapterBuffer = IntPtr.Zero;
|
||||
int size = Marshal.SizeOf(OSAdapterInfoData);
|
||||
AdapterBuffer = Marshal.AllocCoTaskMem((int)size);
|
||||
Marshal.StructureToPtr(OSAdapterInfoData, AdapterBuffer, false);
|
||||
|
||||
if (null != ADL.ADL_Adapter_AdapterInfo_Get)
|
||||
ADLRet = delAdapterInfo(AdapterBuffer, size);
|
||||
if (ADL.ADL_SUCCESS == ADLRet)
|
||||
{
|
||||
ADLRet = ADL.ADL_Adapter_AdapterInfo_Get(AdapterBuffer, size);
|
||||
if (ADL.ADL_SUCCESS == ADLRet)
|
||||
OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());
|
||||
int IsActive = 0;
|
||||
|
||||
var delActive = ADL.GetDelegate<ADL.ADL_Adapter_Active_Get>();
|
||||
|
||||
for (int i = 0; i < NumberOfAdapters; i++)
|
||||
{
|
||||
OSAdapterInfoData = (ADLAdapterInfoArray)Marshal.PtrToStructure(AdapterBuffer, OSAdapterInfoData.GetType());
|
||||
int IsActive = 0;
|
||||
// Check if the adapter is active
|
||||
if (null != delActive)
|
||||
ADLRet = delActive(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
|
||||
|
||||
for (int i = 0; i < NumberOfAdapters; i++)
|
||||
if (ADL.ADL_SUCCESS == ADLRet)
|
||||
{
|
||||
// Check if the adapter is active
|
||||
if (null != ADL.ADL_Adapter_Active_Get)
|
||||
ADLRet = ADL.ADL_Adapter_Active_Get(OSAdapterInfoData.ADLAdapterInfo[i].AdapterIndex, ref IsActive);
|
||||
|
||||
if (ADL.ADL_SUCCESS == ADLRet)
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("ADL_Adapter_AdapterInfo_Get() returned error code " + ADLRet.ToString());
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Debug("ADL_Adapter_AdapterInfo_Get() returned error code " + ADLRet.ToString());
|
||||
}
|
||||
// Release the memory for the AdapterInfo structure
|
||||
if (IntPtr.Zero != AdapterBuffer)
|
||||
@@ -88,7 +174,7 @@ namespace ColorControl
|
||||
return null;
|
||||
}
|
||||
|
||||
public static List<ADLDisplayInfo> GetAllDisplays()
|
||||
public static List<ADLDisplayInfo> GetAllDisplays(bool connected = true)
|
||||
{
|
||||
int ADLRet;
|
||||
int NumberOfDisplays = 0;
|
||||
@@ -104,24 +190,28 @@ namespace ColorControl
|
||||
|
||||
ADLDisplayInfo oneDisplayInfo = new ADLDisplayInfo();
|
||||
|
||||
if (null != ADL.ADL_Display_DisplayInfo_Get)
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_DisplayInfo_Get>();
|
||||
|
||||
if (null != del)
|
||||
{
|
||||
IntPtr DisplayBuffer = IntPtr.Zero;
|
||||
int j = 0;
|
||||
|
||||
// Force the display detection and get the Display Info. Use 0 as last parameter to NOT force detection
|
||||
ADLRet = ADL.ADL_Display_DisplayInfo_Get(primaryAdapter.AdapterIndex, ref NumberOfDisplays, out DisplayBuffer, 1);
|
||||
ADLRet = del(primaryAdapter.AdapterIndex, ref NumberOfDisplays, out DisplayBuffer, 1);
|
||||
if (ADL.ADL_SUCCESS == ADLRet)
|
||||
{
|
||||
for (j = 0; j < NumberOfDisplays; j++)
|
||||
{
|
||||
oneDisplayInfo = (ADLDisplayInfo)Marshal.PtrToStructure(new IntPtr(DisplayBuffer.ToInt32() + j * Marshal.SizeOf(oneDisplayInfo)), oneDisplayInfo.GetType());
|
||||
DisplayInfoData.Add(oneDisplayInfo);
|
||||
oneDisplayInfo = (ADLDisplayInfo)Marshal.PtrToStructure(new IntPtr(DisplayBuffer.ToInt64() + j * Marshal.SizeOf(oneDisplayInfo)), oneDisplayInfo.GetType());
|
||||
if (!connected || (1 == (oneDisplayInfo.DisplayInfoValue & 1))) {
|
||||
DisplayInfoData.Add(oneDisplayInfo);
|
||||
}
|
||||
}
|
||||
Console.WriteLine("\nTotal Number of Displays supported: " + NumberOfDisplays.ToString());
|
||||
Console.WriteLine("\nDispID AdpID Type OutType CnctType Connected Mapped InfoValue DisplayName ");
|
||||
Logger.Debug("Total Number of Displays supported: " + NumberOfDisplays.ToString());
|
||||
Logger.Debug("DispID DispPhyId AdpID Type OutType CnctType Connected Mapped InfoValue DisplayName ");
|
||||
|
||||
for (j = 0; j < NumberOfDisplays; j++)
|
||||
for (j = 0; j < DisplayInfoData.Count; j++)
|
||||
{
|
||||
int InfoValue = DisplayInfoData[j].DisplayInfoValue;
|
||||
string StrConnected = (1 == (InfoValue & 1)) ? "Yes" : "No ";
|
||||
@@ -129,21 +219,21 @@ namespace ColorControl
|
||||
int AdpID = DisplayInfoData[j].DisplayID.DisplayLogicalAdapterIndex;
|
||||
string StrAdpID = (AdpID < 0) ? "--" : AdpID.ToString("d2");
|
||||
|
||||
Console.WriteLine(DisplayInfoData[j].DisplayID.DisplayLogicalIndex.ToString() + " " +
|
||||
StrAdpID + " " +
|
||||
DisplayInfoData[j].DisplayType.ToString() + " " +
|
||||
DisplayInfoData[j].DisplayOutputType.ToString() + " " +
|
||||
DisplayInfoData[j].DisplayConnector.ToString() + " " +
|
||||
StrConnected + " " +
|
||||
StrMapped + " " +
|
||||
InfoValue.ToString("x4") + " " +
|
||||
DisplayInfoData[j].DisplayName.ToString());
|
||||
Logger.Debug(DisplayInfoData[j].DisplayID.DisplayLogicalIndex.ToString() + " " +
|
||||
DisplayInfoData[j].DisplayID.DisplayPhysicalIndex.ToString() + " " +
|
||||
StrAdpID + " " +
|
||||
DisplayInfoData[j].DisplayType.ToString() + " " +
|
||||
DisplayInfoData[j].DisplayOutputType.ToString() + " " +
|
||||
DisplayInfoData[j].DisplayConnector.ToString() + " " +
|
||||
StrConnected + " " +
|
||||
StrMapped + " " +
|
||||
InfoValue.ToString("x4") + " " +
|
||||
DisplayInfoData[j].DisplayName.ToString());
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine("ADL_Display_DisplayInfo_Get() returned error code " + ADLRet.ToString());
|
||||
Logger.Debug("ADL_Display_DisplayInfo_Get() returned error code " + ADLRet.ToString());
|
||||
}
|
||||
// Release the memory for the DisplayInfo structure
|
||||
if (IntPtr.Zero != DisplayBuffer)
|
||||
@@ -152,17 +242,155 @@ namespace ColorControl
|
||||
return DisplayInfoData;
|
||||
}
|
||||
|
||||
public static bool GetDisplayResolution(string displayName, ref int horizontal, ref int vertical)
|
||||
private static bool CheckError(int ADLRet, string functionName)
|
||||
{
|
||||
var displays = GetAllDisplays();
|
||||
var display = displays.FirstOrDefault(d => d.DisplayName.Equals(displayName, StringComparison.OrdinalIgnoreCase));
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && ADL.ADL_Display_Size_Get != null)
|
||||
{
|
||||
int lpDefaultWidth, lpDefaultHeight, lpMinWidth, lpMinHeight, lpMaxWidth, lpMaxHeight, lpStepWidth, lpStepHeight;
|
||||
lpDefaultWidth = lpDefaultHeight = lpMinWidth = lpMinHeight = lpMaxWidth = lpMaxHeight = lpStepWidth = lpStepHeight = 0;
|
||||
var ADLRet = ADL.ADL_Display_Size_Get(display.DisplayID.DisplayPhysicalAdapterIndex, display.DisplayID.DisplayPhysicalIndex, ref horizontal, ref vertical, ref lpDefaultWidth, ref lpDefaultHeight, ref lpMinWidth, ref lpMinHeight, ref lpMaxWidth, ref lpMaxHeight, ref lpStepWidth, ref lpStepHeight);
|
||||
var result = ADLRet == ADL.ADL_SUCCESS;
|
||||
|
||||
return ADLRet == ADL.ADL_SUCCESS;
|
||||
if (!result)
|
||||
{
|
||||
Logger.Error($"Error calling ADL ({functionName}): {ADLRet}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static bool GetDisplayResolution(ADLDisplayInfo display, ref int horizontal, ref int vertical)
|
||||
{
|
||||
var screen = Screen.PrimaryScreen;
|
||||
var bounds = screen.Bounds;
|
||||
|
||||
horizontal = bounds.Width;
|
||||
vertical = bounds.Height;
|
||||
|
||||
Logger.Debug($"GetDisplayResolution: {horizontal}x{vertical}");
|
||||
|
||||
//var del = ADL.GetDelegate<ADL.ADL_Display_Size_Get>();
|
||||
|
||||
//if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
//{
|
||||
// int lpDefaultWidth, lpDefaultHeight, lpMinWidth, lpMinHeight, lpMaxWidth, lpMaxHeight, lpStepWidth, lpStepHeight;
|
||||
// lpDefaultWidth = lpDefaultHeight = lpMinWidth = lpMinHeight = lpMaxWidth = lpMaxHeight = lpStepWidth = lpStepHeight = 0;
|
||||
// var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref horizontal, ref vertical, ref lpDefaultWidth, ref lpDefaultHeight, ref lpMinWidth, ref lpMinHeight, ref lpMaxWidth, ref lpMaxHeight, ref lpStepWidth, ref lpStepHeight);
|
||||
|
||||
// return CheckError(ADLRet, nameof(ADL.ADL_Display_Size_Get));
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static bool GetDisplayPixelFormat(ADLDisplayInfo display, ref ADLPixelFormat pixelFormat)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_PixelFormat_Get>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
int pixelFormatInt = 0;
|
||||
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref pixelFormatInt);
|
||||
|
||||
pixelFormat = (ADLPixelFormat)pixelFormatInt;
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL_Display_PixelFormat_Get));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool SetDisplayPixelFormat(ADLDisplayInfo display, ADLPixelFormat pixelFormat)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_PixelFormat_Set>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)pixelFormat);
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL_Display_PixelFormat_Set));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool GetDisplayColorDepth(ADLDisplayInfo display, ref ADLColorDepth colorDepth)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_ColorDepth_Get>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
int colorDepthInt = 0;
|
||||
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref colorDepthInt);
|
||||
|
||||
colorDepth = (ADLColorDepth)colorDepthInt;
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL_Display_ColorDepth_Get));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool SetDisplayColorDepth(ADLDisplayInfo display, ADLColorDepth colorDepth)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_ColorDepth_Set>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)colorDepth);
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL_Display_ColorDepth_Set));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool GetDisplayDitherState(ADLDisplayInfo display, ref ADLDitherState ditherState)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_DitherState_Get>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
var ditherStateInt = 0;
|
||||
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, ref ditherStateInt);
|
||||
|
||||
ditherState = (ADLDitherState)ditherStateInt;
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL_Display_DitherState_Get));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool SetDisplayDitherState(ADLDisplayInfo display, ADLDitherState ditherState)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL_Display_DitherState_Set>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
var ADLRet = del(display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID.DisplayLogicalIndex, (int)ditherState);
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL_Display_DitherState_Set));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool GetDisplayHDRState(ADLDisplayInfo display, ref bool supported, ref bool enabled)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL2_Display_HDRState_Get>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
var supportedInt = 0;
|
||||
var enabledInt = 0;
|
||||
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID, ref supportedInt, ref enabledInt);
|
||||
|
||||
supported = supportedInt != 0;
|
||||
enabled = enabledInt != 0;
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL2_Display_HDRState_Get));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool SetDisplayHDRState(ADLDisplayInfo display, bool enabled)
|
||||
{
|
||||
var del = ADL.GetDelegate<ADL.ADL2_Display_HDRState_Set>();
|
||||
|
||||
if (display.DisplayID.DisplayPhysicalIndex >= 0 && del != null)
|
||||
{
|
||||
var ADLRet = del(context, display.DisplayID.DisplayLogicalAdapterIndex, display.DisplayID, enabled ? 1 : 0);
|
||||
|
||||
return CheckError(ADLRet, nameof(ADL.ADL2_Display_HDRState_Set));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using ATI.ADL;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class AmdDisplayInfo
|
||||
{
|
||||
public ADLDisplayInfo Display { get; }
|
||||
|
||||
public List<string> Values { get; }
|
||||
|
||||
public string InfoLine { get; }
|
||||
|
||||
public AmdDisplayInfo(ADLDisplayInfo display, List<string> values, string infoLine)
|
||||
{
|
||||
Display = display;
|
||||
Values = values;
|
||||
InfoLine = infoLine;
|
||||
}
|
||||
}
|
||||
}
|
||||
+48
-91
@@ -1,6 +1,4 @@
|
||||
using NvAPIWrapper.Display;
|
||||
using NvAPIWrapper.Native.Display;
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
|
||||
@@ -9,22 +7,23 @@ namespace ColorControl
|
||||
class AmdPreset : PresetBase
|
||||
{
|
||||
public bool applyColorData { get; set; }
|
||||
public ColorData colorData { get; set; }
|
||||
public ADLColorDepth colorDepth { get; set; }
|
||||
public ADLPixelFormat pixelFormat { get; set; }
|
||||
public bool applyHDR { get; set; }
|
||||
public bool HDREnabled { get; set; }
|
||||
public bool toggleHDR { get; set; }
|
||||
public bool applyDithering { get; set; }
|
||||
public bool ditheringEnabled { get; set; }
|
||||
public ADLDitherState ditherState { get; set; }
|
||||
public bool applyRefreshRate { get; set; }
|
||||
public uint refreshRate { get; set; }
|
||||
public bool primaryDisplay { get; set; }
|
||||
public string displayName { get; set; }
|
||||
|
||||
public AmdPreset()
|
||||
public AmdPreset() : base()
|
||||
{
|
||||
applyColorData = true;
|
||||
applyDithering = false;
|
||||
ditheringEnabled = true;
|
||||
ditherState = ADLDitherState.DRIVER_DEFAULT;
|
||||
applyHDR = false;
|
||||
HDREnabled = false;
|
||||
toggleHDR = false;
|
||||
@@ -33,12 +32,6 @@ namespace ColorControl
|
||||
primaryDisplay = true;
|
||||
}
|
||||
|
||||
public AmdPreset(ColorData colorData) : this()
|
||||
{
|
||||
id = GetNewId();
|
||||
this.colorData = colorData;
|
||||
}
|
||||
|
||||
public AmdPreset(AmdPreset preset): this()
|
||||
{
|
||||
id = GetNewId();
|
||||
@@ -46,15 +39,15 @@ namespace ColorControl
|
||||
primaryDisplay = preset.primaryDisplay;
|
||||
displayName = preset.displayName;
|
||||
|
||||
var colorData = preset.colorData;
|
||||
this.colorData = new ColorData(colorData.ColorFormat, dynamicRange: colorData.DynamicRange, colorDepth: colorData.ColorDepth, colorSelectionPolicy: colorData.SelectionPolicy);
|
||||
applyColorData = preset.applyColorData;
|
||||
colorDepth = preset.colorDepth;
|
||||
pixelFormat = preset.pixelFormat;
|
||||
|
||||
applyHDR = preset.applyHDR;
|
||||
HDREnabled = preset.HDREnabled;
|
||||
toggleHDR = preset.toggleHDR;
|
||||
applyDithering = preset.applyDithering;
|
||||
ditheringEnabled = preset.ditheringEnabled;
|
||||
ditherState = preset.ditherState;
|
||||
applyRefreshRate = preset.applyRefreshRate;
|
||||
refreshRate = preset.refreshRate;
|
||||
}
|
||||
@@ -69,28 +62,26 @@ namespace ColorControl
|
||||
public static string[] GetColumnNames()
|
||||
{
|
||||
//return new[] { "BPC", "Format", "Dynamic range", "Toggle HDR", "Shortcut" };
|
||||
return new[] { "Display|140", "Color settings (BPC, format, dyn. range, color space)|260", "Refresh rate|100", "Dithering", "HDR", "Shortcut" };
|
||||
return new[] { "Name", "Display|140", "Color settings (BPC, format)|260", "Refresh rate|100", "Dithering", "HDR", "Shortcut", "Apply on startup" };
|
||||
}
|
||||
|
||||
public List<string> GetDisplayValues()
|
||||
public override List<string> GetDisplayValues(Config config = null)
|
||||
{
|
||||
var values = new List<string>();
|
||||
|
||||
values.Add(name);
|
||||
|
||||
var display = string.Format("{0}", primaryDisplay ? "Primary" : displayName);
|
||||
values.Add(display);
|
||||
|
||||
var colorSettings = string.Format("{0}: {1}, {2}, {3}, {4}", applyColorData ? "Included" : "Excluded", colorData.ColorDepth, colorData.ColorFormat, colorData.DynamicRange, colorData.Colorimetry);
|
||||
var colorSettings = string.Format("{0}: {1}, {2}", applyColorData ? "Included" : "Excluded", colorDepth, pixelFormat);
|
||||
|
||||
values.Add(colorSettings);
|
||||
values.Add(string.Format("{0}: {1}Hz", applyRefreshRate ? "Included" : "Excluded", refreshRate));
|
||||
values.Add(string.Format("{0}: {1}", applyDithering ? "Included" : "Excluded", ditheringEnabled ? "Enabled" : "Disabled"));
|
||||
values.Add(string.Format("{0}: {1}", applyDithering ? "Included" : "Excluded", ditherState));
|
||||
values.Add(string.Format("{0}: {1}", applyHDR ? "Included" : "Excluded", toggleHDR ? "Toggle" : HDREnabled ? "Enabled" : "Disabled"));
|
||||
|
||||
//values.Add(colorData.ColorDepth.ToString());
|
||||
//values.Add(colorData.ColorFormat.ToString());
|
||||
//values.Add(colorData.DynamicRange.ToString());
|
||||
//values.Add(toggleHDR.ToString());
|
||||
values.Add(shortcut);
|
||||
values.Add(string.Format("{0}", config?.AmdPresetId_ApplyOnStartup == id ? "Yes" : string.Empty));
|
||||
|
||||
return values;
|
||||
}
|
||||
@@ -99,21 +90,11 @@ namespace ColorControl
|
||||
{
|
||||
var presets = new List<AmdPreset>();
|
||||
|
||||
presets.Add(new AmdPreset(new ColorData(ColorDataFormat.Auto, dynamicRange: ColorDataDynamicRange.Auto, colorDepth: ColorDataDepth.Default, colorSelectionPolicy: ColorDataSelectionPolicy.BestQuality)));
|
||||
var preset = new AmdPreset();
|
||||
preset.colorDepth = ADLColorDepth.BPC8;
|
||||
preset.pixelFormat = ADLPixelFormat.RGB_FULL_RANGE;
|
||||
|
||||
for (var dynamicRange = ColorDataDynamicRange.VESA; dynamicRange <= ColorDataDynamicRange.CEA; dynamicRange++)
|
||||
{
|
||||
presets.Add(new AmdPreset(new ColorData(ColorDataFormat.RGB, dynamicRange: dynamicRange, colorDepth: ColorDataDepth.BPC8, colorSelectionPolicy: ColorDataSelectionPolicy.User)));
|
||||
presets.Add(new AmdPreset(new ColorData(ColorDataFormat.RGB, dynamicRange: dynamicRange, colorDepth: ColorDataDepth.BPC10, colorSelectionPolicy: ColorDataSelectionPolicy.User)));
|
||||
presets.Add(new AmdPreset(new ColorData(ColorDataFormat.RGB, dynamicRange: dynamicRange, colorDepth: ColorDataDepth.BPC12, colorSelectionPolicy: ColorDataSelectionPolicy.User)));
|
||||
}
|
||||
|
||||
for (var format = ColorDataFormat.YUV422; format <= ColorDataFormat.YUV420; format++)
|
||||
{
|
||||
presets.Add(new AmdPreset(new ColorData(format, dynamicRange: ColorDataDynamicRange.Auto, colorDepth: ColorDataDepth.BPC8, colorSelectionPolicy: ColorDataSelectionPolicy.User)));
|
||||
presets.Add(new AmdPreset(new ColorData(format, dynamicRange: ColorDataDynamicRange.Auto, colorDepth: ColorDataDepth.BPC10, colorSelectionPolicy: ColorDataSelectionPolicy.User)));
|
||||
presets.Add(new AmdPreset(new ColorData(format, dynamicRange: ColorDataDynamicRange.Auto, colorDepth: ColorDataDepth.BPC12, colorSelectionPolicy: ColorDataSelectionPolicy.User)));
|
||||
}
|
||||
presets.Add(preset);
|
||||
|
||||
return presets;
|
||||
}
|
||||
@@ -121,66 +102,42 @@ namespace ColorControl
|
||||
public string GetTextForMenuItem()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
if (displayName != null)
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
{
|
||||
sb.AppendFormat("Display: {0} / ", displayName);
|
||||
}
|
||||
if (applyColorData)
|
||||
{
|
||||
var colorSettings = string.Format("Format: {0}, {1}, {2}", colorData.ColorDepth, colorData.ColorFormat, colorData.DynamicRange);
|
||||
sb.Append(colorSettings);
|
||||
sb.Append(name);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyRefreshRate)
|
||||
else
|
||||
{
|
||||
sb.AppendFormat("{0}Hz", refreshRate);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyDithering)
|
||||
{
|
||||
sb.AppendFormat("Dithering: {0}", ditheringEnabled ? "Yes" : "No");
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyHDR)
|
||||
{
|
||||
sb.AppendFormat("HDR: {0}", toggleHDR ? "Toggle" : HDREnabled ? "Enabled" : "Disabled");
|
||||
sb.Append(" / ");
|
||||
if (displayName != null)
|
||||
{
|
||||
sb.AppendFormat("Display: {0} / ", displayName);
|
||||
}
|
||||
if (applyColorData)
|
||||
{
|
||||
var colorSettings = string.Format("Format: {0}, {1}", colorDepth, pixelFormat);
|
||||
sb.Append(colorSettings);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyRefreshRate)
|
||||
{
|
||||
sb.AppendFormat("{0}Hz", refreshRate);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyDithering)
|
||||
{
|
||||
sb.AppendFormat("Dithering: {0}", ditherState);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyHDR)
|
||||
{
|
||||
sb.AppendFormat("HDR: {0}", toggleHDR ? "Toggle" : HDREnabled ? "Enabled" : "Disabled");
|
||||
sb.Append(" / ");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.ToString(0, Math.Max(0, sb.Length - 3));
|
||||
}
|
||||
|
||||
public static ColorData GenerateColorData(IDictionary<string, object> dictionary)
|
||||
{
|
||||
var format = ColorDataFormat.RGB;
|
||||
var dynamicRange = ColorDataDynamicRange.VESA;
|
||||
var colorDepth = ColorDataDepth.BPC8;
|
||||
var colorimetry = ColorDataColorimetry.Auto;
|
||||
var selectionPolicy = ColorDataSelectionPolicy.User;
|
||||
object value;
|
||||
if (dictionary.TryGetValue("ColorFormat", out value))
|
||||
{
|
||||
format = (ColorDataFormat)Enum.ToObject(typeof(ColorDataFormat), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("ColorDepth", out value))
|
||||
{
|
||||
colorDepth = (ColorDataDepth)Enum.ToObject(typeof(ColorDataDepth), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("Colorimetry", out value))
|
||||
{
|
||||
colorimetry = (ColorDataColorimetry)Enum.ToObject(typeof(ColorDataColorimetry), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("DynamicRange", out value))
|
||||
{
|
||||
dynamicRange = (ColorDataDynamicRange)Enum.ToObject(typeof(ColorDataDynamicRange), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("SelectionPolicy", out value))
|
||||
{
|
||||
selectionPolicy = (ColorDataSelectionPolicy)Enum.ToObject(typeof(ColorDataSelectionPolicy), value);
|
||||
}
|
||||
return new ColorData(format, dynamicRange: dynamicRange, colorimetry: colorimetry, colorDepth: colorDepth, colorSelectionPolicy: selectionPolicy);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
+277
-47
@@ -1,86 +1,224 @@
|
||||
//using ATI.ADL;
|
||||
using ATI.ADL;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class AmdService : GraphicsService
|
||||
class AmdService : GraphicsService<AmdPreset>
|
||||
{
|
||||
private string CurrentDisplay;
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public AmdService()
|
||||
private ADLDisplayInfo _currentDisplay;
|
||||
|
||||
public AmdService(string dataPath) : base(dataPath, "AmdPresets.json")
|
||||
{
|
||||
LoadPresets();
|
||||
}
|
||||
|
||||
public static bool ExecutePresetAsync(string idOrName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var service = new AmdService(Program.DataDir);
|
||||
|
||||
var result = service.ApplyPreset(idOrName);
|
||||
|
||||
if (!result)
|
||||
{
|
||||
Console.WriteLine("Preset not found or error while executing.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Error executing preset: " + ex.ToLogString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
protected override List<AmdPreset> GetDefaultPresets()
|
||||
{
|
||||
return AmdPreset.GetDefaultPresets();
|
||||
}
|
||||
|
||||
private void SavePresets()
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonConvert.SerializeObject(_presets);
|
||||
File.WriteAllText(_presetsFilename, json);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error(e.ToLogString());
|
||||
}
|
||||
}
|
||||
|
||||
public void GlobalSave()
|
||||
{
|
||||
SavePresets();
|
||||
}
|
||||
|
||||
public override bool HasDisplaysAttached(bool reinitialize = false)
|
||||
{
|
||||
try
|
||||
{
|
||||
return GetDisplays().Any();
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public void SetCurrentDisplay(AmdPreset preset)
|
||||
{
|
||||
CurrentDisplay = preset.displayName;
|
||||
var displays = GetDisplays();
|
||||
if (preset.primaryDisplay)
|
||||
{
|
||||
_currentDisplay = displays.FirstOrDefault();
|
||||
}
|
||||
else
|
||||
{
|
||||
_currentDisplay = displays.FirstOrDefault(x => x.DisplayName.Equals(preset.displayName));
|
||||
}
|
||||
}
|
||||
|
||||
public string GetCurrentDisplay()
|
||||
public ADLDisplayInfo GetCurrentDisplay()
|
||||
{
|
||||
return CurrentDisplay;
|
||||
if (string.IsNullOrEmpty(_currentDisplay.DisplayName))
|
||||
{
|
||||
_currentDisplay = GetDisplays().FirstOrDefault();
|
||||
}
|
||||
|
||||
return _currentDisplay;
|
||||
}
|
||||
|
||||
public bool ApplyPreset(AmdPreset preset, Config config)
|
||||
public bool ApplyPreset(string idOrName)
|
||||
{
|
||||
var preset = GetPresetByIdOrName(idOrName);
|
||||
if (preset != null)
|
||||
{
|
||||
return ApplyPreset(preset, Program.AppContext);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ApplyPreset(AmdPreset preset, AppContext appContext)
|
||||
{
|
||||
SetCurrentDisplay(preset);
|
||||
|
||||
if (string.IsNullOrEmpty(_currentDisplay.DisplayName))
|
||||
{
|
||||
Logger.Error("Could not set current display");
|
||||
return false;
|
||||
}
|
||||
|
||||
var result = true;
|
||||
|
||||
if (preset.applyHDR)
|
||||
{
|
||||
if (preset.toggleHDR || preset.HDREnabled != IsHDREnabled())
|
||||
var hdrEnabled = IsHDREnabled();
|
||||
if (preset.toggleHDR)
|
||||
{
|
||||
ToggleHDR(config.DisplaySettingsDelay);
|
||||
result = ADLWrapper.SetDisplayHDRState(_currentDisplay, !hdrEnabled);
|
||||
}
|
||||
else
|
||||
{
|
||||
result = ADLWrapper.SetDisplayHDRState(_currentDisplay, preset.HDREnabled);
|
||||
}
|
||||
|
||||
//if (preset.toggleHDR || preset.HDREnabled != hdrEnabled)
|
||||
//{
|
||||
// ToggleHDR(config.DisplaySettingsDelay);
|
||||
//}
|
||||
}
|
||||
|
||||
if (preset.applyRefreshRate)
|
||||
{
|
||||
SetRefreshRate(preset.refreshRate);
|
||||
if (!SetRefreshRate(preset.refreshRate))
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (preset.applyColorData)
|
||||
{
|
||||
var display = GetCurrentDisplay();
|
||||
// TODO: ADL call to set color format, depth, space
|
||||
// ADL_Display_PixelFormat_Set
|
||||
// ADL_Display_ColorDepth_Set
|
||||
|
||||
//var data = new ColorData(ColorDataFormat.YUV444, ColorDataColorimetry.YCC709, ColorDataDynamicRange.Auto, ColorDataDepth.BPC8, preset.colorData.SelectionPolicy, ColorDataDesktopDepth.Default);
|
||||
//display.DisplayDevice.SetColorData(preset.colorData);
|
||||
if (!ADLWrapper.SetDisplayColorDepth(_currentDisplay, preset.colorDepth))
|
||||
{
|
||||
Logger.Error("Could not set color depth");
|
||||
result = false;
|
||||
}
|
||||
if (preset.pixelFormat != ADLPixelFormat.UNKNOWN && !ADLWrapper.SetDisplayPixelFormat(_currentDisplay, preset.pixelFormat))
|
||||
{
|
||||
Logger.Error("Could not set pixel format");
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (preset.applyDithering)
|
||||
{
|
||||
SetDithering(preset.ditheringEnabled);
|
||||
if (!SetDithering(preset.ditherState))
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
_lastAppliedPreset = preset;
|
||||
|
||||
PresetApplied();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void SetDithering(bool enabled)
|
||||
public bool SetDithering(ADLDitherState ditherState)
|
||||
{
|
||||
// TODO: ADL call to set dithering state
|
||||
// ADL_Display_DitherState_Get
|
||||
var display = GetCurrentDisplay();
|
||||
|
||||
return ADLWrapper.SetDisplayDitherState(display, ditherState);
|
||||
}
|
||||
|
||||
public bool GetDithering()
|
||||
public ADLDitherState GetDithering(ADLDisplayInfo display = default(ADLDisplayInfo))
|
||||
{
|
||||
// TODO: ADL call to get dithering state
|
||||
// ADL_Display_DitherState_Set
|
||||
return false;
|
||||
if (string.IsNullOrEmpty(display.DisplayName))
|
||||
{
|
||||
display = GetCurrentDisplay();
|
||||
}
|
||||
|
||||
var ditherState = ADLDitherState.DRIVER_DEFAULT;
|
||||
|
||||
if (ADLWrapper.GetDisplayDitherState(display, ref ditherState))
|
||||
{
|
||||
return ditherState;
|
||||
}
|
||||
|
||||
return ditherState;
|
||||
}
|
||||
|
||||
public string GetDisplayDeviceName(ADLDisplayInfo display)
|
||||
{
|
||||
return Screen.PrimaryScreen.DeviceName;
|
||||
}
|
||||
|
||||
public bool SetRefreshRate(uint refreshRate)
|
||||
{
|
||||
var portrait = false;
|
||||
var horizontal = 3840;
|
||||
var vertical = 2160;
|
||||
var display = GetCurrentDisplay();
|
||||
|
||||
//ADLWrapper.GetDisplayResolution(display, ref horizontal, ref vertical);
|
||||
ADLWrapper.GetDisplayResolution(display, ref horizontal, ref vertical);
|
||||
|
||||
return SetRefreshRateInternal(display, refreshRate, portrait, horizontal, vertical);
|
||||
var portrait = vertical > horizontal;
|
||||
|
||||
return SetRefreshRateInternal(GetDisplayDeviceName(display), refreshRate, portrait, horizontal, vertical);
|
||||
}
|
||||
|
||||
public List<uint> GetAvailableRefreshRates(AmdPreset preset = null)
|
||||
@@ -90,43 +228,135 @@ namespace ColorControl
|
||||
SetCurrentDisplay(preset);
|
||||
}
|
||||
|
||||
var portrait = false;
|
||||
var horizontal = 3840;
|
||||
var vertical = 2160;
|
||||
var display = GetCurrentDisplay();
|
||||
|
||||
//ADLWrapper.GetDisplayResolution(display, ref horizontal, ref vertical);
|
||||
ADLWrapper.GetDisplayResolution(display, ref horizontal, ref vertical);
|
||||
|
||||
return GetAvailableRefreshRatesInternal(display, portrait, horizontal, vertical);
|
||||
var portrait = vertical > horizontal;
|
||||
|
||||
return GetAvailableRefreshRatesInternal(GetDisplayDeviceName(display), portrait, horizontal, vertical);
|
||||
}
|
||||
|
||||
public bool IsHDREnabled()
|
||||
{
|
||||
// TODO: ADL call to get HDR state
|
||||
//var displayDevice = GetCurrentDisplay().DisplayDevice;
|
||||
//var hdr = displayDevice.HDRColorData;
|
||||
//return hdr?.HDRMode == ColorDataHDRMode.UHDA;
|
||||
return false;
|
||||
var display = GetCurrentDisplay();
|
||||
|
||||
var supported = false;
|
||||
var enabled = false;
|
||||
ADLWrapper.GetDisplayHDRState(display, ref supported, ref enabled);
|
||||
|
||||
Logger.Debug($"IsHDREnabled: supported {supported}, enabled {enabled}");
|
||||
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public List<string> GetDisplays()
|
||||
public List<ADLDisplayInfo> GetDisplays()
|
||||
{
|
||||
//return ADLWrapper.GetAllDisplays();
|
||||
return null;
|
||||
var displays = ADLWrapper.GetAllDisplays();
|
||||
|
||||
//if (!displays.Any())
|
||||
//{
|
||||
// displays.Add(new ADLDisplayInfo
|
||||
// {
|
||||
// DisplayName = "Dummy"
|
||||
// });
|
||||
//}
|
||||
|
||||
return displays;
|
||||
}
|
||||
|
||||
public string GetFullDisplayName(ADLDisplayInfo display)
|
||||
{
|
||||
var name = display.DisplayName;
|
||||
|
||||
var screen = GetScreenForDisplay(display);
|
||||
if (screen != null)
|
||||
{
|
||||
name = $"{screen.DeviceName} ({name})";
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
public Screen GetScreenForDisplay(ADLDisplayInfo display)
|
||||
{
|
||||
var index = 0;
|
||||
foreach (var screen in Screen.AllScreens)
|
||||
{
|
||||
Logger.Debug($"SCREEN[{index}]: {screen.DeviceName}, {screen.DeviceFriendlyName()}, {screen.Primary}");
|
||||
index++;
|
||||
}
|
||||
return Screen.AllScreens.FirstOrDefault(x => x.DeviceFriendlyName().Equals(display.DisplayName));
|
||||
}
|
||||
|
||||
public List<AmdDisplayInfo> GetDisplayInfos()
|
||||
{
|
||||
List<ADLDisplayInfo> displays;
|
||||
try
|
||||
{
|
||||
displays = GetDisplays();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error while getting displays: " + e.ToLogString());
|
||||
return null;
|
||||
}
|
||||
|
||||
var list = new List<AmdDisplayInfo>();
|
||||
|
||||
foreach (var display in displays)
|
||||
{
|
||||
var values = new List<string>();
|
||||
|
||||
values.Add("Current settings");
|
||||
|
||||
var screen = GetScreenForDisplay(display);
|
||||
|
||||
var name = GetFullDisplayName(display);
|
||||
values.Add(name);
|
||||
|
||||
var colorDepth = ADLColorDepth.UNKNOWN;
|
||||
ADLWrapper.GetDisplayColorDepth(display, ref colorDepth);
|
||||
|
||||
var pixelFormat = ADLPixelFormat.UNKNOWN;
|
||||
ADLWrapper.GetDisplayPixelFormat(display, ref pixelFormat);
|
||||
|
||||
var colorSettings = $"{colorDepth}, {pixelFormat}";
|
||||
values.Add(colorSettings);
|
||||
|
||||
var refreshRate = GetCurrentRefreshRate(screen?.DeviceName);
|
||||
values.Add($"{refreshRate}Hz");
|
||||
|
||||
var ditherState = GetDithering(display);
|
||||
values.Add(ditherState.ToString());
|
||||
|
||||
var hdrEnabled = IsHDREnabled();
|
||||
values.Add(hdrEnabled ? "Yes" : "No");
|
||||
|
||||
var infoLine = string.Format("{0}: {1}, {2}Hz, HDR: {3}", name, colorSettings, refreshRate, hdrEnabled ? "Yes" : "No");
|
||||
|
||||
var displayInfo = new AmdDisplayInfo(display, values, infoLine);
|
||||
|
||||
list.Add(displayInfo);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
|
||||
protected override void Initialize()
|
||||
{
|
||||
//if (!ADLWrapper.Initialize())
|
||||
//{
|
||||
// throw new InvalidOperationException("Cannot load AMD API");
|
||||
//}
|
||||
throw new InvalidOperationException("Cannot load AMD API");
|
||||
if (!ADLWrapper.Initialize())
|
||||
{
|
||||
throw new InvalidOperationException("Cannot load AMD API");
|
||||
}
|
||||
}
|
||||
|
||||
protected override void Uninitialize()
|
||||
{
|
||||
//ADLWrapper.Uninitialze();
|
||||
ADLWrapper.Uninitialze();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
{
|
||||
"$schema": "https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json",
|
||||
"version": "2.1.0",
|
||||
"runs": [
|
||||
{
|
||||
"tool": {
|
||||
"driver": {
|
||||
"name": "Dependency Analysis",
|
||||
"semanticVersion": "0.3.261602",
|
||||
"informationUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview",
|
||||
"rules": [
|
||||
{
|
||||
"id": "UA103",
|
||||
"name": "ReferenceToBeDeleted",
|
||||
"fullDescription": {
|
||||
"text": "References that need to be deleted in order to upgrade the project to chosen TFM"
|
||||
},
|
||||
"helpUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
|
||||
},
|
||||
{
|
||||
"id": "UA106",
|
||||
"name": "PackageToBeAdded",
|
||||
"fullDescription": {
|
||||
"text": "Packages that need to be added in order to upgrade the project to chosen TFM"
|
||||
},
|
||||
"helpUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
|
||||
},
|
||||
{
|
||||
"id": "UA108",
|
||||
"name": "FrameworkReferenceToBeAdded",
|
||||
"fullDescription": {
|
||||
"text": "Framework Reference that need to be added in order to upgrade the project to chosen TFM"
|
||||
},
|
||||
"helpUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"ruleId": "UA103",
|
||||
"message": {
|
||||
"text": "Reference to System.Configuration needs to be deleted."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA103",
|
||||
"message": {
|
||||
"text": "Reference to System.ServiceModel needs to be deleted."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA103",
|
||||
"message": {
|
||||
"text": "Reference to System.Web needs to be deleted."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA103",
|
||||
"message": {
|
||||
"text": "Reference to System.Web.Extensions needs to be deleted."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.Configuration.ConfigurationManager, Version=5.0.0 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.ServiceModel.Primitives, Version=4.8.1 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.ServiceModel.Http, Version=4.8.1 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.ServiceModel.Duplex, Version=4.8.1 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.ServiceModel.NetTcp, Version=4.8.1 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.ServiceModel.Security, Version=4.8.1 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package System.ServiceModel.Federation, Version=4.8.1 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers, Version=0.3.261602 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA106",
|
||||
"message": {
|
||||
"text": "Package Microsoft.Windows.Compatibility, Version=6.0.0 needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"ruleId": "UA108",
|
||||
"message": {
|
||||
"text": "Framework Reference to Microsoft.AspNetCore.App needs to be added."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/ColorControl.csproj"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"columnKind": "utf16CodeUnits"
|
||||
},
|
||||
{
|
||||
"tool": {
|
||||
"driver": {
|
||||
"name": "API Upgradability",
|
||||
"semanticVersion": "0.3.261602",
|
||||
"informationUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview"
|
||||
}
|
||||
},
|
||||
"results": [],
|
||||
"columnKind": "utf16CodeUnits"
|
||||
},
|
||||
{
|
||||
"tool": {
|
||||
"driver": {
|
||||
"name": "Component Analysis",
|
||||
"semanticVersion": "0.3.261602",
|
||||
"informationUri": "https://docs.microsoft.com/en-us/dotnet/core/porting/upgrade-assistant-overview",
|
||||
"rules": [
|
||||
{
|
||||
"id": "UA202",
|
||||
"name": "Microsoft.DotNet.UpgradeAssistant.Extensions.Windows.WinformsDpiSettingUpdater",
|
||||
"fullDescription": {
|
||||
"text": "Winforms Source Updater"
|
||||
},
|
||||
"helpUri": "about:blank"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"results": [
|
||||
{
|
||||
"ruleId": "UA202",
|
||||
"message": {
|
||||
"text": "HighDpiMode needs to set in Main() instead of app.config or app.manifest - Application.SetHighDpiMode(HighDpiMode.<setting>). It is recommended to use SystemAware as the HighDpiMode option for better results."
|
||||
},
|
||||
"locations": [
|
||||
{
|
||||
"physicalLocation": {
|
||||
"artifactLocation": {
|
||||
"uri": "file:///C:/Users/vinni/source/repos/ColorControl/ColorControl/Program.cs"
|
||||
},
|
||||
"region": {}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"columnKind": "utf16CodeUnits"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
|
||||
</startup>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
|
||||
</dependentAssembly>
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Runtime.CompilerServices.Unsafe" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.0.6.0" newVersion="4.0.6.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
<System.Windows.Forms.ApplicationConfigurationSection>
|
||||
<add key="DpiAwareness" value="PerMonitorV2" />
|
||||
</System.Windows.Forms.ApplicationConfigurationSection>
|
||||
</configuration>
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace ColorControl
|
||||
{
|
||||
public class AppContext
|
||||
{
|
||||
public static AppContext CurrentContext { get; private set; }
|
||||
|
||||
public Config Config { get; private set; }
|
||||
|
||||
public StartUpParams StartUpParams { get; private set; }
|
||||
|
||||
public AppContext(Config config, StartUpParams startUpParams)
|
||||
{
|
||||
Config = config;
|
||||
StartUpParams = startUpParams;
|
||||
|
||||
CurrentContext = this;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,564 @@
|
||||
using NWin32;
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
// This class takes care of wrapping "Connecting and Configuring Displays(CCD) Win32 API"
|
||||
internal static class CCD
|
||||
{
|
||||
public enum DisplayTopology
|
||||
{
|
||||
Internal,
|
||||
External,
|
||||
Extend,
|
||||
Clone
|
||||
}
|
||||
|
||||
public static DisplayTopology GetDisplayTopology()
|
||||
{
|
||||
uint numPathArrayElements;
|
||||
uint numModeInfoArrayElements;
|
||||
|
||||
NativeMethods.GetDisplayConfigBufferSizes(QueryDisplayFlags.DatabaseCurrent, out numPathArrayElements, out numModeInfoArrayElements);
|
||||
|
||||
var pathArray = new DisplayConfigPathInfo[numPathArrayElements];
|
||||
var modeArray = new DisplayConfigModeInfo[numModeInfoArrayElements];
|
||||
|
||||
DisplayConfigTopologyId displayTopology;
|
||||
|
||||
NativeMethods.QueryDisplayConfig(QueryDisplayFlags.DatabaseCurrent, ref numPathArrayElements, pathArray, ref numModeInfoArrayElements, modeArray, out displayTopology);
|
||||
|
||||
switch (displayTopology)
|
||||
{
|
||||
case DisplayConfigTopologyId.External: return DisplayTopology.External;
|
||||
case DisplayConfigTopologyId.Internal: return DisplayTopology.Internal;
|
||||
case DisplayConfigTopologyId.Extend: return DisplayTopology.Extend;
|
||||
}
|
||||
|
||||
return DisplayTopology.Clone;
|
||||
}
|
||||
|
||||
public static void SetDisplayTopology(DisplayTopology displayTopology)
|
||||
{
|
||||
switch (displayTopology)
|
||||
{
|
||||
case DisplayTopology.External:
|
||||
NativeMethods.SetDisplayConfig(0, null, 0, null, (SdcFlags.Apply | SdcFlags.TopologyExternal));
|
||||
break;
|
||||
case DisplayTopology.Internal:
|
||||
NativeMethods.SetDisplayConfig(0, null, 0, null, (SdcFlags.Apply | SdcFlags.TopologyInternal));
|
||||
break;
|
||||
case DisplayTopology.Extend:
|
||||
NativeMethods.SetDisplayConfig(0, null, 0, null, (SdcFlags.Apply | SdcFlags.TopologyExtend));
|
||||
break;
|
||||
case DisplayTopology.Clone:
|
||||
NativeMethods.SetDisplayConfig(0, null, 0, null, (SdcFlags.Apply | SdcFlags.TopologyClone));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public static void SetHDRState(bool enabled, string displayName = null)
|
||||
{
|
||||
uint pathCount, modeCount;
|
||||
|
||||
var err = NativeMethods.GetDisplayConfigBufferSizes(QueryDisplayFlags.OnlyActivePaths, out pathCount, out modeCount);
|
||||
if (err == NativeConstants.ERROR_SUCCESS)
|
||||
{
|
||||
var pathsArray = new DisplayConfigPathInfo[pathCount];
|
||||
var modesArray = new DisplayConfigModeInfo[modeCount];
|
||||
|
||||
DisplayConfigTopologyId displayTopology;
|
||||
|
||||
err = NativeMethods.QueryDisplayConfig(QueryDisplayFlags.DatabaseCurrent, ref pathCount, pathsArray, ref modeCount, modesArray, out displayTopology);
|
||||
if (err == NativeConstants.ERROR_SUCCESS)
|
||||
{
|
||||
foreach (var path in pathsArray)
|
||||
{
|
||||
// get display name
|
||||
var info = new DISPLAYCONFIG_SOURCE_DEVICE_NAME();
|
||||
info.header.type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME;
|
||||
info.header.size = Marshal.SizeOf<DISPLAYCONFIG_SOURCE_DEVICE_NAME>();
|
||||
info.header.adapterId = path.sourceInfo.adapterId;
|
||||
info.header.id = path.sourceInfo.id;
|
||||
|
||||
err = NativeMethods.DisplayConfigGetDeviceInfo(ref info);
|
||||
if (err != NativeConstants.ERROR_SUCCESS)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
var deviceName = info.viewGdiDeviceName;
|
||||
if (displayName != null && !EqualDisplayNames(deviceName, displayName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var setpacket = new DISPLAYCONFIG_SET_ADVANCED_COLOR_INFO();
|
||||
setpacket.header = new DISPLAYCONFIG_DEVICE_INFO_HEADER();
|
||||
setpacket.header.type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE;
|
||||
setpacket.header.size = Marshal.SizeOf<DISPLAYCONFIG_SET_ADVANCED_COLOR_INFO>(); ;
|
||||
|
||||
var requestpacket = new DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO();
|
||||
requestpacket.header = new DISPLAYCONFIG_DEVICE_INFO_HEADER();
|
||||
requestpacket.header.type = DISPLAYCONFIG_DEVICE_INFO_TYPE.DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO;
|
||||
requestpacket.header.size = Marshal.SizeOf<DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO>(); ;
|
||||
|
||||
for (int i = 0; i < modeCount; i++)
|
||||
{
|
||||
if (modesArray[i].infoType == DisplayConfigModeInfoType.Target)
|
||||
{
|
||||
setpacket.header.adapterId = modesArray[i].adapterId;
|
||||
setpacket.header.id = modesArray[i].id;
|
||||
requestpacket.header.adapterId = modesArray[i].adapterId;
|
||||
requestpacket.header.id = modesArray[i].id;
|
||||
|
||||
if (NativeMethods.DisplayConfigGetDeviceInfo(ref requestpacket) == NativeConstants.ERROR_SUCCESS)
|
||||
{
|
||||
if (requestpacket.advancedColorSupported)
|
||||
{
|
||||
setpacket.enableAdvancedColor = enabled ? 1U : 0;
|
||||
NativeMethods.DisplayConfigSetDeviceInfo(ref setpacket);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (err != NativeConstants.ERROR_SUCCESS)
|
||||
{
|
||||
throw new Win32Exception(err);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool EqualDisplayNames(string displayName1, string displayName2)
|
||||
{
|
||||
displayName1 = displayName1.Replace("\\", string.Empty);
|
||||
displayName2 = displayName2.Replace("\\", string.Empty);
|
||||
|
||||
return displayName1.Equals(displayName2, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
private enum DISPLAYCONFIG_MODE_INFO_TYPE
|
||||
{
|
||||
DISPLAYCONFIG_MODE_INFO_TYPE_SOURCE = 1,
|
||||
DISPLAYCONFIG_MODE_INFO_TYPE_TARGET = 2,
|
||||
DISPLAYCONFIG_MODE_INFO_TYPE_DESKTOP_IMAGE = 3,
|
||||
}
|
||||
|
||||
private enum DISPLAYCONFIG_DEVICE_INFO_TYPE
|
||||
{
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME = 1,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME = 2,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_PREFERRED_MODE = 3,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_ADAPTER_NAME = 4,
|
||||
DISPLAYCONFIG_DEVICE_INFO_SET_TARGET_PERSISTENCE = 5,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_BASE_TYPE = 6,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SUPPORT_VIRTUAL_RESOLUTION = 7,
|
||||
DISPLAYCONFIG_DEVICE_INFO_SET_SUPPORT_VIRTUAL_RESOLUTION = 8,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_ADVANCED_COLOR_INFO = 9,
|
||||
DISPLAYCONFIG_DEVICE_INFO_SET_ADVANCED_COLOR_STATE = 10,
|
||||
DISPLAYCONFIG_DEVICE_INFO_GET_SDR_WHITE_LEVEL = 11,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DISPLAYCONFIG_DEVICE_INFO_HEADER
|
||||
{
|
||||
public DISPLAYCONFIG_DEVICE_INFO_TYPE type;
|
||||
public int size;
|
||||
public LUID adapterId;
|
||||
public uint id;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct LUID
|
||||
{
|
||||
uint LowPart;
|
||||
uint HighPart;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigVideoOutputTechnology : uint
|
||||
{
|
||||
Other = 4294967295, // -1
|
||||
Hd15 = 0,
|
||||
Svideo = 1,
|
||||
CompositeVideo = 2,
|
||||
ComponentVideo = 3,
|
||||
Dvi = 4,
|
||||
Hdmi = 5,
|
||||
Lvds = 6,
|
||||
DJpn = 8,
|
||||
Sdi = 9,
|
||||
DisplayportExternal = 10,
|
||||
DisplayportEmbedded = 11,
|
||||
UdiExternal = 12,
|
||||
UdiEmbedded = 13,
|
||||
Sdtvdongle = 14,
|
||||
Internal = 0x80000000,
|
||||
ForceUint32 = 0xFFFFFFFF
|
||||
}
|
||||
|
||||
#region SdcFlags enum
|
||||
|
||||
[Flags]
|
||||
enum SdcFlags : uint
|
||||
{
|
||||
Zero = 0,
|
||||
|
||||
TopologyInternal = 0x00000001,
|
||||
TopologyClone = 0x00000002,
|
||||
TopologyExtend = 0x00000004,
|
||||
TopologyExternal = 0x00000008,
|
||||
TopologySupplied = 0x00000010,
|
||||
|
||||
UseSuppliedDisplayConfig = 0x00000020,
|
||||
Validate = 0x00000040,
|
||||
Apply = 0x00000080,
|
||||
NoOptimization = 0x00000100,
|
||||
SaveToDatabase = 0x00000200,
|
||||
AllowChanges = 0x00000400,
|
||||
PathPersistIfRequired = 0x00000800,
|
||||
ForceModeEnumeration = 0x00001000,
|
||||
AllowPathOrderChanges = 0x00002000,
|
||||
|
||||
UseDatabaseCurrent = TopologyInternal | TopologyClone | TopologyExtend | TopologyExternal
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigFlags : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
PathActive = 0x00000001
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigSourceStatus
|
||||
{
|
||||
Zero = 0x0,
|
||||
InUse = 0x00000001
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigTargetStatus : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
|
||||
InUse = 0x00000001,
|
||||
FORCIBLE = 0x00000002,
|
||||
ForcedAvailabilityBoot = 0x00000004,
|
||||
ForcedAvailabilityPath = 0x00000008,
|
||||
ForcedAvailabilitySystem = 0x00000010,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigRotation : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
|
||||
Identity = 1,
|
||||
Rotate90 = 2,
|
||||
Rotate180 = 3,
|
||||
Rotate270 = 4,
|
||||
ForceUint32 = 0xFFFFFFFF
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigPixelFormat : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
|
||||
Pixelformat8Bpp = 1,
|
||||
Pixelformat16Bpp = 2,
|
||||
Pixelformat24Bpp = 3,
|
||||
Pixelformat32Bpp = 4,
|
||||
PixelformatNongdi = 5,
|
||||
PixelformatForceUint32 = 0xffffffff
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigScaling : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
|
||||
Identity = 1,
|
||||
Centered = 2,
|
||||
Stretched = 3,
|
||||
Aspectratiocenteredmax = 4,
|
||||
Custom = 5,
|
||||
Preferred = 128,
|
||||
ForceUint32 = 0xFFFFFFFF
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigRational
|
||||
{
|
||||
uint numerator;
|
||||
uint denominator;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigScanLineOrdering : uint
|
||||
{
|
||||
Unspecified = 0,
|
||||
Progressive = 1,
|
||||
Interlaced = 2,
|
||||
InterlacedUpperfieldfirst = Interlaced,
|
||||
InterlacedLowerfieldfirst = 3,
|
||||
ForceUint32 = 0xFFFFFFFF
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigPathInfo
|
||||
{
|
||||
public DisplayConfigPathSourceInfo sourceInfo;
|
||||
public DisplayConfigPathTargetInfo targetInfo;
|
||||
public uint flags;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigModeInfoType : uint
|
||||
{
|
||||
Zero = 0,
|
||||
|
||||
Source = 1,
|
||||
Target = 2,
|
||||
ForceUint32 = 0xFFFFFFFF
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Explicit)]
|
||||
struct DisplayConfigModeInfo
|
||||
{
|
||||
[FieldOffset(0)]
|
||||
public DisplayConfigModeInfoType infoType;
|
||||
|
||||
[FieldOffset(4)]
|
||||
public uint id;
|
||||
|
||||
[FieldOffset(8)]
|
||||
public LUID adapterId;
|
||||
|
||||
[FieldOffset(16)]
|
||||
public DisplayConfigTargetMode targetMode;
|
||||
|
||||
[FieldOffset(16)]
|
||||
public DisplayConfigSourceMode sourceMode;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfig2DRegion
|
||||
{
|
||||
uint cx;
|
||||
uint cy;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum D3DmdtVideoSignalStandard : uint
|
||||
{
|
||||
Uninitialized = 0,
|
||||
VesaDmt = 1,
|
||||
VesaGtf = 2,
|
||||
VesaCvt = 3,
|
||||
Ibm = 4,
|
||||
Apple = 5,
|
||||
NtscM = 6,
|
||||
NtscJ = 7,
|
||||
Ntsc443 = 8,
|
||||
PalB = 9,
|
||||
PalB1 = 10,
|
||||
PalG = 11,
|
||||
PalH = 12,
|
||||
PalI = 13,
|
||||
PalD = 14,
|
||||
PalN = 15,
|
||||
PalNc = 16,
|
||||
SecamB = 17,
|
||||
SecamD = 18,
|
||||
SecamG = 19,
|
||||
SecamH = 20,
|
||||
SecamK = 21,
|
||||
SecamK1 = 22,
|
||||
SecamL = 23,
|
||||
SecamL1 = 24,
|
||||
Eia861 = 25,
|
||||
Eia861A = 26,
|
||||
Eia861B = 27,
|
||||
PalK = 28,
|
||||
PalK1 = 29,
|
||||
PalL = 30,
|
||||
PalM = 31,
|
||||
Other = 255
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigVideoSignalInfo
|
||||
{
|
||||
long pixelRate;
|
||||
DisplayConfigRational hSyncFreq;
|
||||
DisplayConfigRational vSyncFreq;
|
||||
DisplayConfig2DRegion activeSize;
|
||||
DisplayConfig2DRegion totalSize;
|
||||
|
||||
D3DmdtVideoSignalStandard videoStandard;
|
||||
DisplayConfigScanLineOrdering ScanLineOrdering;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigTargetMode
|
||||
{
|
||||
DisplayConfigVideoSignalInfo targetVideoSignalInfo;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct PointL
|
||||
{
|
||||
int x;
|
||||
int y;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigSourceMode
|
||||
{
|
||||
uint width;
|
||||
uint height;
|
||||
DisplayConfigPixelFormat pixelFormat;
|
||||
PointL position;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigPathSourceInfo
|
||||
{
|
||||
public LUID adapterId;
|
||||
public uint id;
|
||||
public uint modeInfoIdx;
|
||||
|
||||
public DisplayConfigSourceStatus statusFlags;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
struct DisplayConfigPathTargetInfo
|
||||
{
|
||||
public LUID adapterId;
|
||||
public uint id;
|
||||
public uint modeInfoIdx;
|
||||
public DisplayConfigVideoOutputTechnology outputTechnology;
|
||||
public DisplayConfigRotation rotation;
|
||||
public DisplayConfigScaling scaling;
|
||||
public DisplayConfigRational refreshRate;
|
||||
public DisplayConfigScanLineOrdering scanLineOrdering;
|
||||
|
||||
public bool targetAvailable;
|
||||
public DisplayConfigTargetStatus statusFlags;
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum QueryDisplayFlags : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
|
||||
AllPaths = 0x00000001,
|
||||
OnlyActivePaths = 0x00000002,
|
||||
DatabaseCurrent = 0x00000004
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum DisplayConfigTopologyId : uint
|
||||
{
|
||||
Zero = 0x0,
|
||||
|
||||
Internal = 0x00000001,
|
||||
Clone = 0x00000002,
|
||||
Extend = 0x00000004,
|
||||
External = 0x00000008,
|
||||
ForceUint32 = 0xFFFFFFFF
|
||||
}
|
||||
|
||||
private enum DISPLAYCONFIG_COLOR_ENCODING
|
||||
{
|
||||
DISPLAYCONFIG_COLOR_ENCODING_RGB = 0,
|
||||
DISPLAYCONFIG_COLOR_ENCODING_YCBCR444 = 1,
|
||||
DISPLAYCONFIG_COLOR_ENCODING_YCBCR422 = 2,
|
||||
DISPLAYCONFIG_COLOR_ENCODING_YCBCR420 = 3,
|
||||
DISPLAYCONFIG_COLOR_ENCODING_INTENSITY = 4,
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO
|
||||
{
|
||||
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
|
||||
public uint value;
|
||||
public DISPLAYCONFIG_COLOR_ENCODING colorEncoding;
|
||||
public int bitsPerColorChannel;
|
||||
|
||||
public bool advancedColorSupported => (value & 0x1) == 0x1;
|
||||
public bool advancedColorEnabled => (value & 0x2) == 0x2;
|
||||
public bool wideColorEnforced => (value & 0x4) == 0x4;
|
||||
public bool advancedColorForceDisabled => (value & 0x8) == 0x8;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
private struct DISPLAYCONFIG_SET_ADVANCED_COLOR_INFO
|
||||
{
|
||||
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
|
||||
public uint enableAdvancedColor;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS
|
||||
{
|
||||
public uint value;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct DISPLAYCONFIG_TARGET_DEVICE_NAME
|
||||
{
|
||||
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
|
||||
public DISPLAYCONFIG_TARGET_DEVICE_NAME_FLAGS flags;
|
||||
public DisplayConfigVideoOutputTechnology outputTechnology;
|
||||
public ushort edidManufactureId;
|
||||
public ushort edidProductCodeId;
|
||||
public uint connectorInstance;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
|
||||
public string monitorFriendlyDeviceName;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 128)]
|
||||
public string monitorDevicePat;
|
||||
}
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
||||
private struct DISPLAYCONFIG_SOURCE_DEVICE_NAME
|
||||
{
|
||||
public DISPLAYCONFIG_DEVICE_INFO_HEADER header;
|
||||
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
|
||||
public string viewGdiDeviceName;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
static class NativeMethods
|
||||
{
|
||||
[DllImport("User32.dll")]
|
||||
public static extern int GetDisplayConfigBufferSizes(QueryDisplayFlags flags, out uint numPathArrayElements, out uint numModeInfoArrayElements);
|
||||
|
||||
[DllImport("User32.dll")]
|
||||
public static extern int SetDisplayConfig(uint numPathArrayElements, [In] DisplayConfigPathInfo[] pathArray, uint numModeInfoArrayElements, [In] DisplayConfigModeInfo[] modeInfoArray, SdcFlags flags);
|
||||
|
||||
[DllImport("User32.dll")]
|
||||
public static extern int QueryDisplayConfig(QueryDisplayFlags flags, ref uint numPathArrayElements, [In, Out] DisplayConfigPathInfo[] pathInfoArray, ref uint modeInfoArrayElements, [In, Out] DisplayConfigModeInfo[] modeInfoArray, out DisplayConfigTopologyId id);
|
||||
|
||||
[DllImport("user32")]
|
||||
public static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_GET_ADVANCED_COLOR_INFO requestPacket);
|
||||
|
||||
[DllImport("user32")]
|
||||
public static extern int DisplayConfigSetDeviceInfo(ref DISPLAYCONFIG_SET_ADVANCED_COLOR_INFO setPacket);
|
||||
|
||||
[DllImport("user32")]
|
||||
public static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_TARGET_DEVICE_NAME requestPacket);
|
||||
|
||||
[DllImport("user32")]
|
||||
public static extern int DisplayConfigGetDeviceInfo(ref DISPLAYCONFIG_SOURCE_DEVICE_NAME requestPacket);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{A6005D08-70F0-44CB-A384-9219EBA84F21}</ProjectGuid>
|
||||
<TargetFramework>net6.0-windows10.0.20348.0</TargetFramework>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<RootNamespace>ColorControl</RootNamespace>
|
||||
<AssemblyName>ColorControl</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
@@ -26,234 +16,52 @@
|
||||
<UpdateUrl>https://www.maassoft.com/downloads/ColorControl/</UpdateUrl>
|
||||
<ProductName>ColorControl</ProductName>
|
||||
<PublisherName>Maassoft</PublisherName>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.3.6.0</ApplicationVersion>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<Company>Maassoft</Company>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>5.5.0.0</ApplicationVersion>
|
||||
<Version>5.5.0.0</Version>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<PublishWizardCompleted>true</PublishWizardCompleted>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<BootstrapperEnabled>false</BootstrapperEnabled>
|
||||
<GenerateAssemblyInfo>true</GenerateAssemblyInfo>
|
||||
<UseWindowsForms>true</UseWindowsForms>
|
||||
<UseWPF>false</UseWPF>
|
||||
<ImportWindowsDesktopTargets>true</ImportWindowsDesktopTargets>
|
||||
<ApplicationIcon>pngbarn.ico</ApplicationIcon>
|
||||
<SupportedOSPlatformVersion>10.0.17763.0</SupportedOSPlatformVersion>
|
||||
<Copyright>2020-2022 Maassoft</Copyright>
|
||||
<Authors>Maassoft</Authors>
|
||||
<ManifestCertificateThumbprint>CF0BC153EA664CD97AC6F234B91F45D34630958F</ManifestCertificateThumbprint>
|
||||
<ManifestKeyFile>ColorControl_1_TemporaryKey.pfx</ManifestKeyFile>
|
||||
<GenerateManifests>true</GenerateManifests>
|
||||
<TargetZone>LocalIntranet</TargetZone>
|
||||
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
|
||||
<SignManifests>true</SignManifests>
|
||||
<AssemblyOriginatorKeyFile>ColorControl_TemporaryKey.pfx</AssemblyOriginatorKeyFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<OutputPath>bin\x64\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<DebugType>full</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
|
||||
<OutputPath>bin\x64\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<Optimize>true</Optimize>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<PlatformTarget>x64</PlatformTarget>
|
||||
<LangVersion>7.3</LangVersion>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ManifestCertificateThumbprint>482C987E8C69872608C9D44751E004C5784E8540</ManifestCertificateThumbprint>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ManifestKeyFile>ColorControl_TemporaryKey.pfx</ManifestKeyFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<GenerateManifests>true</GenerateManifests>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<TargetZone>LocalIntranet</TargetZone>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<SignManifests>true</SignManifests>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<SignAssembly>false</SignAssembly>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<AssemblyOriginatorKeyFile>ColorControl_TemporaryKey.pfx</AssemblyOriginatorKeyFile>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ApplicationIcon>pngbarn.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Microsoft.Win32.TaskScheduler, Version=2.8.20.0, Culture=neutral, PublicKeyToken=c416bc1b32d97233, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\TaskScheduler.2.8.20\lib\net452\Microsoft.Win32.TaskScheduler.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Native, Version=0.1.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Native.0.1.0\lib\net35\Native.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NLog.4.7.2\lib\net45\NLog.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NStandard, Version=0.4.3.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NStandard.0.4.3\lib\net46\NStandard.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NvAPIWrapper, Version=0.8.0.98, Culture=neutral, PublicKeyToken=310fd07b25df79b3, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NvAPIWrapper.Net.0.8.0.98\lib\net45\NvAPIWrapper.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="NWin32, Version=1.0.6.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\NWin32.1.0.6\lib\net46\NWin32.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="PacketDotNet, Version=1.0.5.0, Culture=neutral, PublicKeyToken=451414c7667b2a58, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\PacketDotNet.1.0.5\lib\net45\PacketDotNet.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="SharpPcap, Version=5.2.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\SharpPcap.5.2.0\lib\netstandard2.0\SharpPcap.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Buffers, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Buffers.4.5.1\lib\net461\System.Buffers.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Configuration" />
|
||||
<Reference Include="System.Configuration.Install" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.IO.Compression" />
|
||||
<Reference Include="System.Memory, Version=4.0.1.1, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Memory.4.5.4\lib\net461\System.Memory.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Numerics" />
|
||||
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.CompilerServices.Unsafe, Version=4.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Runtime.CompilerServices.Unsafe.4.7.0\lib\netstandard2.0\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Runtime.Serialization" />
|
||||
<Reference Include="System.Runtime.WindowsRuntime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL">
|
||||
<SpecificVersion>False</SpecificVersion>
|
||||
<HintPath>..\..\..\..\..\..\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.ServiceModel" />
|
||||
<Reference Include="System.ServiceProcess" />
|
||||
<Reference Include="System.Transactions" />
|
||||
<Reference Include="System.Web" />
|
||||
<Reference Include="System.Web.Extensions" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Deployment" />
|
||||
<Reference Include="System.Drawing" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Windows.Forms" />
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="Windows">
|
||||
<HintPath>..\..\..\..\..\..\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.18362.0\Windows.winmd</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="WindowsBase" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="GraphicsService.cs" />
|
||||
<Compile Include="AmdService.cs" />
|
||||
<Compile Include="AmdPreset.cs" />
|
||||
<Compile Include="StartUpParams.cs" />
|
||||
<Compile Include="LgServiceConfig.cs" />
|
||||
<Compile Include="WOL.cs" />
|
||||
<Compile Include="RestartDetector.cs" />
|
||||
<Compile Include="ExceptionExtensions.cs" />
|
||||
<Compile Include="lgtv\App.cs" />
|
||||
<Compile Include="lgtv\Channel.cs" />
|
||||
<Compile Include="lgtv\ClientKeyStore.cs" />
|
||||
<Compile Include="lgtv\ExternalInput.cs" />
|
||||
<Compile Include="lgtv\IsConnectedDelegate.cs" />
|
||||
<Compile Include="lgtv\LgTvApi.cs" />
|
||||
<Compile Include="lgtv\LgTvConnection.cs" />
|
||||
<Compile Include="lgtv\LgWebOsMouseService.cs" />
|
||||
<Compile Include="lgtv\MessageType.cs" />
|
||||
<Compile Include="lgtv\RawRequestMessage.cs" />
|
||||
<Compile Include="lgtv\RequestMessage.cs" />
|
||||
<Compile Include="PnpDev.cs" />
|
||||
<Compile Include="TreeNodeBuilder.cs" />
|
||||
<Compile Include="ColorDataConverter.cs" />
|
||||
<Compile Include="Config.cs" />
|
||||
<Compile Include="lgtv\LgApp.cs" />
|
||||
<Compile Include="PresetBase.cs" />
|
||||
<Compile Include="LgPreset.cs" />
|
||||
<Compile Include="NvPreset.cs" />
|
||||
<Compile Include="LgService.cs" />
|
||||
<Compile Include="NvService.cs" />
|
||||
<Compile Include="ScreenInterrogatory.cs" />
|
||||
<Compile Include="Utils.cs" />
|
||||
<Compile Include="MainForm.cs">
|
||||
<SubType>Form</SubType>
|
||||
</Compile>
|
||||
<Compile Include="MainForm.Designer.cs">
|
||||
<DependentUpon>MainForm.cs</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<EmbeddedResource Include="MainForm.resx">
|
||||
<DependentUpon>MainForm.cs</DependentUpon>
|
||||
</EmbeddedResource>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
<SubType>Designer</SubType>
|
||||
</EmbeddedResource>
|
||||
<Compile Include="Properties\Resources.Designer.cs">
|
||||
<Compile Update="Properties\Settings.Designer.cs">
|
||||
<DesignTimeSharedInput>True</DesignTimeSharedInput>
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
<DependentUpon>Settings.settings</DependentUpon>
|
||||
</Compile>
|
||||
<None Include="ColorControl_TemporaryKey.pfx" />
|
||||
<Compile Update="RemoteControlPanel.cs">
|
||||
<SubType>UserControl</SubType>
|
||||
</Compile>
|
||||
<EmbeddedResource Include="Resources\LG_register.json" />
|
||||
<EmbeddedResource Include="Resources\RC_coords.txt" />
|
||||
<EmbeddedResource Include="Resources\LG_remote.jpg" />
|
||||
<Content Include="LgPresets.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
<None Include="lgtv\README.md" />
|
||||
<None Include="packages.config" />
|
||||
<None Include="Properties\app.manifest" />
|
||||
<None Include="Properties\Settings.settings">
|
||||
<Generator>SettingsSingleFileGenerator</Generator>
|
||||
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
|
||||
</None>
|
||||
<Compile Include="Properties\Settings.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Settings.settings</DependentUpon>
|
||||
<DesignTimeSharedInput>True</DesignTimeSharedInput>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include=".NETFramework,Version=v4.7.2">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Microsoft .NET Framework 4.7.2 %28x86 and x64%29</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="pngbarn.ico" />
|
||||
@@ -272,5 +80,22 @@
|
||||
<EmbedInteropTypes>True</EmbedInteropTypes>
|
||||
</COMReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
|
||||
<PackageReference Include="System.Configuration.ConfigurationManager" Version="6.0.0" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
|
||||
<PackageReference Include="NLog" Version="4.7.13" />
|
||||
<PackageReference Include="NStandard" Version="0.8.28" />
|
||||
<PackageReference Include="NvAPIWrapper.Net" Version="0.8.1.101" />
|
||||
<PackageReference Include="NWin32" Version="1.2.0" />
|
||||
<PackageReference Include="TaskScheduler" Version="2.9.3" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Update="Properties\Settings.settings">
|
||||
<Generator>SettingsSingleFileGenerator</Generator>
|
||||
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
@@ -1,54 +1,40 @@
|
||||
using NvAPIWrapper.Display;
|
||||
using NvAPIWrapper.Native.Display;
|
||||
using Newtonsoft.Json;
|
||||
using NvAPIWrapper.Display;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Web.Script.Serialization;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
public class ColorDataConverter : JavaScriptConverter
|
||||
public class ColorDataConverter : JsonConverter<ColorData>
|
||||
{
|
||||
public override IEnumerable<Type> SupportedTypes
|
||||
public override bool CanWrite { get { return false; } }
|
||||
|
||||
public override ColorData ReadJson(JsonReader reader, Type objectType, ColorData existingValue, bool hasExistingValue, JsonSerializer serializer)
|
||||
{
|
||||
get { return new List<Type>() { typeof(ColorData) }; }
|
||||
var result = new Dictionary<string, object>();
|
||||
|
||||
if (reader.TokenType == JsonToken.StartObject)
|
||||
{
|
||||
reader.Read();
|
||||
while (reader.TokenType == JsonToken.PropertyName)
|
||||
{
|
||||
var propertyName = reader.Value;
|
||||
|
||||
reader.Read();
|
||||
var value = reader.Value;
|
||||
|
||||
result.Add(propertyName.ToString(), value);
|
||||
|
||||
reader.Read();
|
||||
}
|
||||
}
|
||||
|
||||
return NvPreset.GenerateColorData(result);
|
||||
}
|
||||
|
||||
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
|
||||
public override void WriteJson(JsonWriter writer, ColorData value, JsonSerializer serializer)
|
||||
{
|
||||
Dictionary<string, object> result = new Dictionary<string, object>();
|
||||
if (obj == null) return result;
|
||||
return result;
|
||||
}
|
||||
|
||||
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
|
||||
{
|
||||
var format = ColorDataFormat.RGB;
|
||||
var dynamicRange = ColorDataDynamicRange.VESA;
|
||||
var colorDepth = ColorDataDepth.BPC8;
|
||||
var colorimetry = ColorDataColorimetry.Auto;
|
||||
var selectionPolicy = ColorDataSelectionPolicy.User;
|
||||
object value;
|
||||
if (dictionary.TryGetValue("ColorFormat", out value))
|
||||
{
|
||||
format = (ColorDataFormat)Enum.ToObject(typeof(ColorDataFormat), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("ColorDepth", out value))
|
||||
{
|
||||
colorDepth = (ColorDataDepth)Enum.ToObject(typeof(ColorDataDepth), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("Colorimetry", out value))
|
||||
{
|
||||
colorimetry = (ColorDataColorimetry)Enum.ToObject(typeof(ColorDataColorimetry), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("DynamicRange", out value))
|
||||
{
|
||||
dynamicRange = (ColorDataDynamicRange)Enum.ToObject(typeof(ColorDataDynamicRange), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("SelectionPolicy", out value))
|
||||
{
|
||||
selectionPolicy = (ColorDataSelectionPolicy)Enum.ToObject(typeof(ColorDataSelectionPolicy), value);
|
||||
}
|
||||
return new ColorData(format, dynamicRange: dynamicRange, colorimetry: colorimetry, colorDepth: colorDepth, colorSelectionPolicy: selectionPolicy, desktopColorDepth: ColorDataDesktopDepth.Default);
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
+11
-5
@@ -1,17 +1,19 @@
|
||||
namespace ColorControl
|
||||
{
|
||||
class Config
|
||||
public class Config
|
||||
{
|
||||
public bool StartMinimized { get; set; }
|
||||
|
||||
public bool MinimizeOnClose { get; set; }
|
||||
|
||||
public bool MinimizeToTray { get; set; }
|
||||
public bool CheckForUpdates { get; set; }
|
||||
public int DisplaySettingsDelay { get; set; }
|
||||
|
||||
public string ScreenSaverShortcut { get; set; }
|
||||
|
||||
public int FormWidth { get; set; }
|
||||
public int FormHeight { get; set; }
|
||||
public int NvPresetId_ApplyOnStartup { get; set; }
|
||||
public int AmdPresetId_ApplyOnStartup { get; set; }
|
||||
public bool FixChromeFonts { get; set; }
|
||||
public bool UseGdiScaling { get; set; }
|
||||
|
||||
public Config()
|
||||
{
|
||||
@@ -19,6 +21,10 @@
|
||||
ScreenSaverShortcut = string.Empty;
|
||||
FormWidth = 900;
|
||||
FormHeight = 600;
|
||||
MinimizeToTray = true;
|
||||
CheckForUpdates = true;
|
||||
FixChromeFonts = false;
|
||||
UseGdiScaling = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,7 @@ namespace ColorControl
|
||||
/// <param name="environmentStackTrace">Environment stack trace, for pulling additional stack frames.</param>
|
||||
public static string ToLogString(this Exception exception, string environmentStackTrace = "")
|
||||
{
|
||||
List<string> environmentStackTraceLines = ExceptionExtensions.GetUserStackTraceLines(environmentStackTrace);
|
||||
List<string> environmentStackTraceLines = GetUserStackTraceLines(environmentStackTrace);
|
||||
if (environmentStackTraceLines.Any())
|
||||
{
|
||||
environmentStackTraceLines.RemoveAt(0);
|
||||
@@ -29,7 +29,14 @@ namespace ColorControl
|
||||
|
||||
string fullStackTrace = String.Join(Environment.NewLine, stackTraceLines);
|
||||
|
||||
string logMessage = exception.Message + Environment.NewLine + fullStackTrace;
|
||||
string logMessage = exception.Message + Environment.NewLine;
|
||||
|
||||
if (exception.InnerException != null)
|
||||
{
|
||||
logMessage += $"Inner exception: {exception.InnerException.Message}{Environment.NewLine}";
|
||||
}
|
||||
|
||||
logMessage += fullStackTrace;
|
||||
return logMessage;
|
||||
}
|
||||
|
||||
@@ -51,7 +58,7 @@ namespace ColorControl
|
||||
List<string> outputList = new List<string>();
|
||||
Regex regex = new Regex(@"([^\)]*\)) in (.*):([A-z]*) (\d)*$");
|
||||
|
||||
List<string> stackTraceLines = ExceptionExtensions.GetStackTraceLines(fullStackTrace);
|
||||
List<string> stackTraceLines = GetStackTraceLines(fullStackTrace);
|
||||
foreach (string stackTraceLine in stackTraceLines)
|
||||
{
|
||||
if (!regex.IsMatch(stackTraceLine))
|
||||
|
||||
@@ -9,13 +9,12 @@ using System.Threading;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class GraphicsService
|
||||
abstract class GraphicsService<T> : ServiceBase<T> where T : PresetBase
|
||||
{
|
||||
protected static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public GraphicsService()
|
||||
public GraphicsService(string dataPath, string presetsBaseFilename) : base(dataPath, presetsBaseFilename)
|
||||
{
|
||||
Initialize();
|
||||
}
|
||||
|
||||
~GraphicsService()
|
||||
@@ -23,15 +22,7 @@ namespace ColorControl
|
||||
Uninitialize();
|
||||
}
|
||||
|
||||
protected virtual void Initialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
protected virtual void Uninitialize()
|
||||
{
|
||||
|
||||
}
|
||||
public abstract bool HasDisplaysAttached(bool reinitialize = false);
|
||||
|
||||
protected void ToggleHDR(int delay = 1000)
|
||||
{
|
||||
@@ -48,6 +39,18 @@ namespace ColorControl
|
||||
}
|
||||
}
|
||||
|
||||
protected void OpenDisplaySettings(int delay = 1000)
|
||||
{
|
||||
Process.Start("ms-settings:display");
|
||||
Thread.Sleep(delay);
|
||||
|
||||
var process = Process.GetProcessesByName("SystemSettings").FirstOrDefault();
|
||||
if (process != null)
|
||||
{
|
||||
System.Windows.Forms.SendKeys.SendWait("%{F4}");
|
||||
}
|
||||
}
|
||||
|
||||
protected bool SetRefreshRateInternal(string displayName, uint refreshRate, bool portrait, int horizontal, int vertical)
|
||||
{
|
||||
uint i = 0;
|
||||
@@ -93,5 +96,15 @@ namespace ColorControl
|
||||
return list;
|
||||
}
|
||||
|
||||
protected uint GetCurrentRefreshRate(string displayName)
|
||||
{
|
||||
DEVMODEA devMode;
|
||||
// NativeMethods defines modeNum as an 'uint' but we need to pass '-1'
|
||||
if (Utils.EnumDisplaySettingsA(displayName, Utils.ENUM_CURRENT_SETTINGS, out devMode))
|
||||
{
|
||||
return devMode.dmDisplayFrequency;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,886 @@
|
||||
using LgTv;
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class LgDevice
|
||||
{
|
||||
public class InvokableAction
|
||||
{
|
||||
public Func<Dictionary<string, object>, bool> Function { get; set; }
|
||||
public string Name { get; set; }
|
||||
public Type EnumType { get; set; }
|
||||
public decimal MinValue { get; set; }
|
||||
public decimal MaxValue { get; set; }
|
||||
public string Category { get; set; }
|
||||
public string Title { get; set; }
|
||||
public int CurrentValue { get; set; }
|
||||
public LgPreset Preset { get; set; }
|
||||
}
|
||||
|
||||
public class LgDevicePictureSettings
|
||||
{
|
||||
public int Backlight { get; set; }
|
||||
public int Contrast { get; set; }
|
||||
public int Brightness { get; set; }
|
||||
public int Color { get; set; }
|
||||
}
|
||||
|
||||
public enum PowerState
|
||||
{
|
||||
Unknown,
|
||||
Active,
|
||||
Power_Off,
|
||||
Suspend,
|
||||
Active_Standby,
|
||||
Screen_Off
|
||||
}
|
||||
|
||||
public enum PowerOffSource
|
||||
{
|
||||
Unknown,
|
||||
App,
|
||||
Manually
|
||||
}
|
||||
|
||||
protected static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
public static Func<string, string[], bool> ExternalServiceHandler;
|
||||
public static List<string> DefaultActionsOnGameBar = new() { "backlight", "contrast", "brightness", "color" };
|
||||
|
||||
public string Name { get; private set; }
|
||||
public string IpAddress { get; private set; }
|
||||
public string MacAddress { get; private set; }
|
||||
public bool IsCustom { get; private set; }
|
||||
[JsonIgnore]
|
||||
public bool IsDummy { get; private set; }
|
||||
|
||||
public bool PowerOnAfterStartup { get; set; }
|
||||
public bool PowerOnAfterResume { get; set; }
|
||||
public bool PowerOffOnShutdown { get; set; }
|
||||
public bool PowerOffOnStandby { get; set; }
|
||||
public bool PowerSwitchOnScreenSaver { get; set; }
|
||||
public bool PowerOnAfterManualPowerOff { get; set; }
|
||||
public bool TriggersEnabled { get; set; }
|
||||
|
||||
private List<string> _actionsForGameBar;
|
||||
|
||||
public List<string> ActionsOnGameBar {
|
||||
get
|
||||
{
|
||||
return _actionsForGameBar;
|
||||
}
|
||||
set
|
||||
{
|
||||
if (value?.Any() == false)
|
||||
{
|
||||
_actionsForGameBar = DefaultActionsOnGameBar;
|
||||
}
|
||||
else
|
||||
{
|
||||
_actionsForGameBar = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[JsonIgnore]
|
||||
public PowerState CurrentState { get; set; }
|
||||
|
||||
[JsonIgnore]
|
||||
private LgTvApi _lgTvApi;
|
||||
[JsonIgnore]
|
||||
private bool _justWokeUp;
|
||||
[JsonIgnore]
|
||||
public PowerOffSource PoweredOffBy { get; private set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool PoweredOffViaApp { get; private set; }
|
||||
[JsonIgnore]
|
||||
private DateTimeOffset _poweredOffViaAppDateTime { get; set; }
|
||||
[JsonIgnore]
|
||||
private List<InvokableAction> _invokableActions = new List<InvokableAction>();
|
||||
[JsonIgnore]
|
||||
private SemaphoreSlim _connectSemaphore = new SemaphoreSlim(1, 1);
|
||||
|
||||
[JsonIgnore]
|
||||
public string ModelName { get; private set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public LgDevicePictureSettings PictureSettings { get; private set; }
|
||||
|
||||
public event EventHandler PictureSettingsChangedEvent;
|
||||
|
||||
[JsonConstructor]
|
||||
public LgDevice(string name, string ipAddress, string macAddress, bool isCustom = true, bool isDummy = false)
|
||||
{
|
||||
PictureSettings = new LgDevicePictureSettings();
|
||||
ActionsOnGameBar = new List<string> { "backlight", "contrast", "brightness", "color" };
|
||||
|
||||
Name = name;
|
||||
IpAddress = ipAddress;
|
||||
MacAddress = macAddress;
|
||||
IsCustom = isCustom;
|
||||
IsDummy = isDummy;
|
||||
TriggersEnabled = true;
|
||||
|
||||
AddInvokableAction("WOL", new Func<Dictionary<string, object>, bool>(WakeAction));
|
||||
AddGenericPictureAction("backlight", minValue: 0, maxValue: 100);
|
||||
AddGenericPictureAction("brightness", minValue: 0, maxValue: 100);
|
||||
AddGenericPictureAction("contrast", minValue: 0, maxValue: 100);
|
||||
AddGenericPictureAction("color", minValue: 0, maxValue: 100);
|
||||
AddGenericPictureAction("pictureMode", typeof(PictureMode), title: "Picture Mode");
|
||||
//AddGenericPictureAction("dynamicRange", typeof(DynamicRange), category: "dimensionInfo", title: "Dynamic Range");
|
||||
AddGenericPictureAction("colorGamut", typeof(ColorGamut), title: "Color Gamut");
|
||||
AddGenericPictureAction("dynamicContrast", typeof(OffToHigh), title: "Dynamic Contrast");
|
||||
AddGenericPictureAction("gamma", typeof(GammaExp));
|
||||
AddGenericPictureAction("whiteBalanceColorTemperature", typeof(WhiteBalanceColorTemperature), title: "White Balance Color Temperature");
|
||||
//AddGenericPictureAction("dynamicColor", typeof(OffToAuto));
|
||||
//AddGenericPictureAction("superResolution", typeof(OffToAuto));
|
||||
AddGenericPictureAction("peakBrightness", typeof(OffToHigh), title: "Peak Brightness");
|
||||
AddGenericPictureAction("smoothGradation", typeof(OffToAuto), title: "Smooth Gradation");
|
||||
AddGenericPictureAction("energySaving", typeof(EnergySaving), title: "Energy Saving");
|
||||
AddGenericPictureAction("hdrDynamicToneMapping", typeof(DynamicTonemapping), title: "HDR Dynamic Tone Mapping");
|
||||
//AddGenericPictureAction("blackLevel", typeof(LowToAuto));
|
||||
//AddGenericPictureAction("ambientLightCompensation", typeof(OffToAuto2));
|
||||
//AddGenericPictureAction("truMotionMode", typeof(TruMotionMode));
|
||||
AddGenericPictureAction("motionProOLED", typeof(OffToHigh), title: "OLED Motion Pro");
|
||||
AddGenericPictureAction("motionPro", typeof(OffToOn), title: "Motion Pro");
|
||||
AddGenericPictureAction("uhdDeepColorHDMI1", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("uhdDeepColorHDMI2", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("uhdDeepColorHDMI3", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("uhdDeepColorHDMI4", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("gameOptimizationHDMI1", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("gameOptimizationHDMI2", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("gameOptimizationHDMI3", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("gameOptimizationHDMI4", typeof(OffToOn), category: "other");
|
||||
//AddGenericPictureAction("freesyncOLEDHDMI4", typeof(OffToOn), category: "other");
|
||||
//AddGenericPictureAction("freesyncSupport", typeof(OffToOn), category: "other");
|
||||
AddGenericPictureAction("hdmiPcMode_hdmi1", typeof(FalseToTrue), category: "other");
|
||||
AddGenericPictureAction("hdmiPcMode_hdmi2", typeof(FalseToTrue), category: "other");
|
||||
AddGenericPictureAction("hdmiPcMode_hdmi3", typeof(FalseToTrue), category: "other");
|
||||
AddGenericPictureAction("hdmiPcMode_hdmi4", typeof(FalseToTrue), category: "other");
|
||||
AddGenericPictureAction("adjustingLuminance", minValue: -50, maxValue: 50);
|
||||
//AddGenericPictureAction("wb20PointsGammaValue", minValue: -50, maxValue: 50);
|
||||
AddInvokableAction("turnScreenOff", new Func<Dictionary<string, object>, bool>(TurnScreenOffAction));
|
||||
AddInvokableAction("turnScreenOn", new Func<Dictionary<string, object>, bool>(TurnScreenOnAction));
|
||||
|
||||
AddInternalPresetAction(new LgPreset("InStart", "com.webos.app.factorywin", new[] { "0", "4", "1", "3" }, new { id = "executeFactory", irKey = "inStart" }));
|
||||
AddInternalPresetAction(new LgPreset("EzAdjust", "com.webos.app.factorywin", new[] { "0", "4", "1", "3" }, new { id = "executeFactory", irKey = "ezAdjust" }));
|
||||
AddInternalPresetAction(new LgPreset("Software Update", "com.webos.app.softwareupdate", null, new { mode = "user", flagUpdate = true }));
|
||||
|
||||
AddSetDeviceConfigAction("HDMI_1_icon", typeof(HdmiIcon), "HDMI 1 icon");
|
||||
AddSetDeviceConfigAction("HDMI_2_icon", typeof(HdmiIcon), "HDMI 2 icon");
|
||||
AddSetDeviceConfigAction("HDMI_3_icon", typeof(HdmiIcon), "HDMI 3 icon");
|
||||
AddSetDeviceConfigAction("HDMI_4_icon", typeof(HdmiIcon), "HDMI 4 icon");
|
||||
|
||||
AddGenericPictureAction("soundMode", typeof(SoundMode), category: "sound", title: "Sound Mode");
|
||||
AddGenericPictureAction("soundOutput", typeof(SoundOutput), category: "sound", title: "Sound Output");
|
||||
//await ExecuteRequest("luna://com.webos.settingsservice/setSystemSettings", new { category = "network", settings = new { wolwowlOnOff = "true" } });
|
||||
AddGenericPictureAction("wolwowlOnOff", typeof(FalseToTrue), category: "network", title: "Wake-On-LAN");
|
||||
}
|
||||
|
||||
private void AddInvokableAction(string name, Func<Dictionary<string, object>, bool> function)
|
||||
{
|
||||
var action = new InvokableAction
|
||||
{
|
||||
Name = name,
|
||||
Function = function
|
||||
};
|
||||
|
||||
_invokableActions.Add(action);
|
||||
}
|
||||
|
||||
private void AddInternalPresetAction(LgPreset preset)
|
||||
{
|
||||
var action = new InvokableAction
|
||||
{
|
||||
Name = preset.name,
|
||||
Preset = preset
|
||||
};
|
||||
|
||||
_invokableActions.Add(action);
|
||||
}
|
||||
|
||||
private void AddGenericPictureAction(string name, Type type = null, decimal minValue = 0, decimal maxValue = 0, string category = "picture", string title = null)
|
||||
{
|
||||
var action = new InvokableAction
|
||||
{
|
||||
Name = name,
|
||||
Function = new Func<Dictionary<string, object>, bool>(GenericPictureAction),
|
||||
EnumType = type,
|
||||
MinValue = minValue,
|
||||
MaxValue = maxValue,
|
||||
Category = category,
|
||||
Title = title == null ? Utils.FirstCharUpperCase(name) : title
|
||||
};
|
||||
|
||||
_invokableActions.Add(action);
|
||||
}
|
||||
|
||||
private void AddSetDeviceConfigAction(string name, Type type, string title)
|
||||
{
|
||||
var action = new InvokableAction
|
||||
{
|
||||
Name = name,
|
||||
Function = new Func<Dictionary<string, object>, bool>(GenericDeviceConfigAction),
|
||||
EnumType = type,
|
||||
Title = title == null ? Utils.FirstCharUpperCase(name) : title
|
||||
};
|
||||
|
||||
_invokableActions.Add(action);
|
||||
}
|
||||
|
||||
public void AddGameBarAction(string name)
|
||||
{
|
||||
if (!ActionsOnGameBar.Contains(name))
|
||||
{
|
||||
ActionsOnGameBar.Add(name);
|
||||
}
|
||||
}
|
||||
|
||||
public void RemoveGameBarAction(string name)
|
||||
{
|
||||
ActionsOnGameBar.Remove(name);
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
//return (IsDummy ? string.Empty : (IsCustom ? "Custom: " : "Auto detect: ")) + $"{Name}" + (!string.IsNullOrEmpty(IpAddress) ? $" ({IpAddress})" : string.Empty);
|
||||
return $"{(IsDummy ? string.Empty : (IsCustom ? "Custom: " : "Auto detect: "))}{Name}{(!string.IsNullOrEmpty(IpAddress) ? ", " + IpAddress : string.Empty)}";
|
||||
}
|
||||
|
||||
public async Task<bool> Connect(int retries = 3)
|
||||
{
|
||||
var locked = _connectSemaphore.CurrentCount == 0;
|
||||
await _connectSemaphore.WaitAsync();
|
||||
try
|
||||
{
|
||||
if (locked && _lgTvApi != null)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
DisposeConnection();
|
||||
_lgTvApi = await LgTvApi.CreateLgTvApi(IpAddress, retries);
|
||||
|
||||
//Test();
|
||||
//_lgTvApi.Test3();
|
||||
if (_lgTvApi != null)
|
||||
{
|
||||
var info = await _lgTvApi.GetSystemInfo("modelName");
|
||||
if (info != null)
|
||||
{
|
||||
ModelName = info.modelName;
|
||||
}
|
||||
|
||||
//await _lgTvApi.SubscribeVolume(VolumeChanged);
|
||||
await _lgTvApi.SubscribePowerState(PowerStateChanged);
|
||||
await _lgTvApi.SubscribePictureSettings(PictureSettingsChanged);
|
||||
|
||||
//await _lgTvApi.Reboot();
|
||||
|
||||
//var result = await GetPictureSettings();
|
||||
|
||||
//await _lgTvApi.SetSystemSettings("adjustingLuminance", new[] { 0, 0, -5, -10, -15, -20, -25, -30, -35, -40, -45, -50, -50, -50, -40, -30, -20, -10, 10, 20, 30, 50 });
|
||||
//await _lgTvApi.SetSystemSettings("adjustingLuminance", new[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 });
|
||||
|
||||
//await _lgTvApi.SetInput("HDMI_1");
|
||||
//await Task.Delay(2000);
|
||||
//await _lgTvApi.SetConfig("com.palm.app.settings.enableHdmiPcLabel", true);
|
||||
//await _lgTvApi.SetInput("HDMI_2");
|
||||
}
|
||||
return _lgTvApi != null;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string logMessage = ex.ToLogString(Environment.StackTrace);
|
||||
Logger.Error($"Error while connecting to {IpAddress}: {logMessage}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
_connectSemaphore.Release();
|
||||
}
|
||||
}
|
||||
|
||||
public bool VolumeChanged(dynamic payload)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool PictureSettingsChanged(dynamic payload)
|
||||
{
|
||||
if (payload.settings != null)
|
||||
{
|
||||
var settings = payload.settings;
|
||||
|
||||
Logger.Debug($"PictureSettingsChanged: {JsonConvert.SerializeObject(settings)}");
|
||||
|
||||
if (settings.backlight != null)
|
||||
{
|
||||
PictureSettings.Backlight = Utils.ParseDynamicAsInt(settings.backlight, PictureSettings.Backlight);
|
||||
}
|
||||
if (settings.contrast != null)
|
||||
{
|
||||
PictureSettings.Contrast = Utils.ParseDynamicAsInt(settings.contrast, PictureSettings.Contrast);
|
||||
}
|
||||
if (settings.brightness != null)
|
||||
{
|
||||
PictureSettings.Brightness = Utils.ParseDynamicAsInt(settings.brightness, PictureSettings.Brightness);
|
||||
}
|
||||
if (settings.color != null)
|
||||
{
|
||||
PictureSettings.Color = Utils.ParseDynamicAsInt(settings.color, PictureSettings.Color);
|
||||
}
|
||||
}
|
||||
|
||||
PictureSettingsChangedEvent?.Invoke(this, EventArgs.Empty);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool PowerStateChanged(dynamic payload)
|
||||
{
|
||||
Logger.Debug($"[{Name}] Power state change: {JsonConvert.SerializeObject(payload)}");
|
||||
|
||||
var state = ((string)payload.state).Replace(' ', '_');
|
||||
|
||||
PowerState newState;
|
||||
if (Enum.TryParse(state, out newState))
|
||||
{
|
||||
CurrentState = newState;
|
||||
|
||||
if (CurrentState == PowerState.Active)
|
||||
{
|
||||
if (payload.processing == null && (DateTimeOffset.Now - _poweredOffViaAppDateTime).TotalMilliseconds > 500)
|
||||
{
|
||||
PoweredOffViaApp = false;
|
||||
PoweredOffBy = PowerOffSource.Unknown;
|
||||
_poweredOffViaAppDateTime = DateTimeOffset.MinValue;
|
||||
}
|
||||
}
|
||||
else {
|
||||
PoweredOffBy = PoweredOffViaApp ? PowerOffSource.App : PowerOffSource.Manually;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
CurrentState = PowerState.Unknown;
|
||||
Logger.Warn($"Unknown power state: {state}");
|
||||
}
|
||||
|
||||
Logger.Debug($"PoweredOffBy: {PoweredOffBy}, PoweredOffViaApp: {PoweredOffViaApp}");
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool IsConnected()
|
||||
{
|
||||
return !_lgTvApi?.ConnectionClosed ?? false;
|
||||
}
|
||||
|
||||
internal void DisposeConnection()
|
||||
{
|
||||
if (_lgTvApi != null)
|
||||
{
|
||||
_lgTvApi.Dispose();
|
||||
_lgTvApi = null;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ExecutePreset(LgPreset preset, bool reconnect, LgServiceConfig config)
|
||||
{
|
||||
var hasApp = !string.IsNullOrEmpty(preset.appId);
|
||||
|
||||
var hasWOL = preset.steps.Any(s => s.Equals("WOL", StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (hasWOL)
|
||||
{
|
||||
var connected = await WakeAndConnect(0);
|
||||
if (!connected)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (var tries = 0; tries <= 1; tries++)
|
||||
{
|
||||
if (!await Connected(reconnect || tries == 1))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hasApp)
|
||||
{
|
||||
try
|
||||
{
|
||||
var @params = preset.AppParams;
|
||||
if (@params == null && config.ShowAdvancedActions)
|
||||
{
|
||||
if (preset.appId.Equals("com.webos.app.softwareupdate"))
|
||||
{
|
||||
@params = new { mode = "user", flagUpdate = true };
|
||||
}
|
||||
else if (preset.appId.Equals("com.webos.app.factorywin"))
|
||||
{
|
||||
if (preset.name.Contains("ezadjust", StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
@params = new { id = "executeFactory", irKey = "ezAdjust" };
|
||||
}
|
||||
else
|
||||
{
|
||||
@params = new { id = "executeFactory", irKey = "inStart" };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await _lgTvApi.LaunchApp(preset.appId, @params);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string logMessage = ex.ToLogString(Environment.StackTrace);
|
||||
Logger.Error("Error while launching app: " + logMessage);
|
||||
|
||||
if (tries == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_justWokeUp)
|
||||
{
|
||||
_justWokeUp = false;
|
||||
await Task.Delay(1000);
|
||||
}
|
||||
}
|
||||
|
||||
if (preset.steps.Any())
|
||||
{
|
||||
if (hasApp)
|
||||
{
|
||||
await Task.Delay(1500);
|
||||
}
|
||||
try
|
||||
{
|
||||
await ExecuteSteps(_lgTvApi, preset);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
string logMessage = ex.ToLogString(Environment.StackTrace);
|
||||
Logger.Error("Error while executing steps: " + logMessage);
|
||||
|
||||
if (tries == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private async Task ExecuteSteps(LgTvApi api, LgPreset preset)
|
||||
{
|
||||
var mouse = await api.GetMouse();
|
||||
foreach (var step in preset.steps)
|
||||
{
|
||||
var keySpec = step.Split(':');
|
||||
var key = keySpec[0].ToUpper();
|
||||
var index = key.IndexOf("(");
|
||||
string[] parameters = null;
|
||||
if (index > -1)
|
||||
{
|
||||
var keyValue = keySpec[0].Split('(');
|
||||
key = keyValue[0];
|
||||
parameters = keyValue[1].Substring(0, keyValue[1].Length - 1).Split(';');
|
||||
}
|
||||
|
||||
var delay = 0;
|
||||
if (keySpec.Length == 2)
|
||||
{
|
||||
delay = Utils.ParseInt(keySpec[1]);
|
||||
}
|
||||
|
||||
var executeKey = true;
|
||||
var action = _invokableActions.FirstOrDefault(a => a.Name.Equals(key, StringComparison.OrdinalIgnoreCase));
|
||||
if (action != null)
|
||||
{
|
||||
ExecuteAction(action, parameters);
|
||||
|
||||
executeKey = false;
|
||||
}
|
||||
if (ExternalServiceHandler != null && parameters != null)
|
||||
{
|
||||
if (ExternalServiceHandler(key, parameters))
|
||||
{
|
||||
executeKey = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (executeKey)
|
||||
{
|
||||
SendKey(mouse, key);
|
||||
delay = delay == 0 ? 180 : delay;
|
||||
}
|
||||
|
||||
if (delay > 0)
|
||||
{
|
||||
await Task.Delay(delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void ExecuteAction(InvokableAction action, string[] parameters)
|
||||
{
|
||||
var function = action.Function;
|
||||
if (function == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (parameters?.Length > 0)
|
||||
{
|
||||
var keyValues = new Dictionary<string, object> {
|
||||
{ "name", action.Name },
|
||||
{ "value", parameters },
|
||||
{ "category", action.Category }
|
||||
};
|
||||
|
||||
function(keyValues);
|
||||
return;
|
||||
}
|
||||
|
||||
function(null);
|
||||
}
|
||||
|
||||
private void SendKey(LgWebOsMouseService mouse, string key)
|
||||
{
|
||||
if (key.Length >= 1 && int.TryParse(key[0].ToString(), out _))
|
||||
{
|
||||
key = "_" + key;
|
||||
}
|
||||
var button = (ButtonType)Enum.Parse(typeof(ButtonType), key);
|
||||
mouse.SendButton(button);
|
||||
}
|
||||
|
||||
public async Task<LgWebOsMouseService> GetMouseAsync()
|
||||
{
|
||||
return await _lgTvApi.GetMouse();
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<LgApp>> GetApps(bool force = false)
|
||||
{
|
||||
if (!await Connected(force))
|
||||
{
|
||||
Logger.Debug("Cannot refresh apps: no connection could be made");
|
||||
return new List<LgApp>();
|
||||
}
|
||||
|
||||
return await _lgTvApi.GetApps(force);
|
||||
}
|
||||
|
||||
internal async Task<bool> PowerOff()
|
||||
{
|
||||
if (!await Connected(true) || CurrentState != PowerState.Active)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
PoweredOffViaApp = true;
|
||||
_poweredOffViaAppDateTime = DateTimeOffset.Now;
|
||||
|
||||
await _lgTvApi.TurnOff();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal async Task<bool> TestConnection(int retries = 1)
|
||||
{
|
||||
if (!await Connected(true, retries))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
await _lgTvApi.IsMuted();
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error("TestConnection: " + ex.ToLogString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<bool> WakeAndConnect(int wakeDelay = 5000, int connectDelay = 500)
|
||||
{
|
||||
try
|
||||
{
|
||||
//if (wakeDelay == 0)
|
||||
//{
|
||||
// if (await ConnectToSelectedDevice())
|
||||
// {
|
||||
// Logger.Debug("Already connected, no wake needed?");
|
||||
// return;
|
||||
// };
|
||||
//}
|
||||
|
||||
await Task.Delay(wakeDelay);
|
||||
var result = Wake();
|
||||
if (!result)
|
||||
{
|
||||
Logger.Debug("WOL failed");
|
||||
return false;
|
||||
}
|
||||
Logger.Debug("WOL succeeded");
|
||||
await Task.Delay(connectDelay);
|
||||
result = await Connect();
|
||||
Logger.Debug("Connect succeeded: " + result);
|
||||
return result;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("WakeAndConnectToSelectedDevice: " + e.ToLogString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal bool Wake()
|
||||
{
|
||||
var result = false;
|
||||
|
||||
if (MacAddress != null)
|
||||
{
|
||||
result = WOL.WakeFunction(MacAddress);
|
||||
_justWokeUp = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Debug("Cannot wake device: the device has no MAC-address");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal async Task<bool> WakeAndConnectWithRetries(int retries = 5)
|
||||
{
|
||||
var wakeDelay = 0;
|
||||
var maxRetries = retries <= 1 ? 5 : retries;
|
||||
|
||||
var result = false;
|
||||
for (var retry = 0; retry < maxRetries && !result; retry++)
|
||||
{
|
||||
Logger.Debug($"WakeAndConnectWithRetries: attempt {retry + 1} of {maxRetries}...");
|
||||
|
||||
var ms = DateTimeOffset.Now.ToUnixTimeMilliseconds();
|
||||
result = await WakeAndConnect(retry == 0 ? wakeDelay : 0);
|
||||
ms = DateTimeOffset.Now.ToUnixTimeMilliseconds() - ms;
|
||||
if (!result)
|
||||
{
|
||||
var delay = 2000 - ms;
|
||||
if (delay > 0)
|
||||
{
|
||||
await Task.Delay((int)delay);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result)
|
||||
{
|
||||
var resumeScript = Path.Combine(Program.DataDir, "ResumeScript.bat");
|
||||
if (File.Exists(resumeScript))
|
||||
{
|
||||
Utils.StartProcess(resumeScript, hidden: true);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public List<InvokableAction> GetInvokableActions()
|
||||
{
|
||||
return _invokableActions;
|
||||
}
|
||||
|
||||
public List<InvokableAction> GetInvokableActionsForGameBar()
|
||||
{
|
||||
var actions = GetInvokableActions();
|
||||
return actions.Where(a => a.Category == "picture" && (a.EnumType != null && a.EnumType != typeof(PictureMode) || a.MinValue >= 0 && a.MaxValue > 0)).ToList();
|
||||
}
|
||||
|
||||
public List<InvokableAction> GetActionsForGameBar()
|
||||
{
|
||||
var actions = GetInvokableActions();
|
||||
return actions.Where(a => ActionsOnGameBar.Contains(a.Name)).ToList();
|
||||
}
|
||||
|
||||
public async Task PowerOn()
|
||||
{
|
||||
var mouse = await _lgTvApi.GetMouse();
|
||||
mouse.SendButton(ButtonType.POWER);
|
||||
}
|
||||
|
||||
public void Test()
|
||||
{
|
||||
try
|
||||
{
|
||||
//_lgTvApi.GetServiceList();
|
||||
//_lgTvApi?.Test();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error("TEST: " + ex.ToLogString());
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> Connected(bool reconnect = false, int retries = 3)
|
||||
{
|
||||
if (reconnect || !IsConnected() || !string.Equals(_lgTvApi.GetIpAddress(), IpAddress))
|
||||
{
|
||||
if (!await Connect(retries))
|
||||
{
|
||||
Logger.Debug("Cannot apply LG-preset: no connection could be made");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void ConvertToCustom()
|
||||
{
|
||||
IsCustom = true;
|
||||
}
|
||||
|
||||
public bool IsUsingHDRPictureMode()
|
||||
{
|
||||
// Temporary workaround because I cannot read the picture mode at this time
|
||||
return PictureSettings.Backlight == 100 && PictureSettings.Contrast == 100;
|
||||
}
|
||||
|
||||
internal async Task SetBacklight(int backlight)
|
||||
{
|
||||
await _lgTvApi.SetSystemSettings("backlight", backlight.ToString());
|
||||
}
|
||||
|
||||
internal async Task SetContrast(int contrast)
|
||||
{
|
||||
await _lgTvApi.SetSystemSettings("contrast", contrast.ToString());
|
||||
}
|
||||
|
||||
public async Task SetOLEDMotionPro(string mode)
|
||||
{
|
||||
await _lgTvApi.SetConfig("tv.model.motionProMode", mode);
|
||||
}
|
||||
|
||||
internal async Task SetConfig(string key, object value)
|
||||
{
|
||||
await _lgTvApi.SetConfig(key, value);
|
||||
}
|
||||
internal async Task SetSystemSettings(string name, string value)
|
||||
{
|
||||
await _lgTvApi.SetSystemSettings(name, value);
|
||||
|
||||
UpdateCurrentValueOfAction(name, value);
|
||||
}
|
||||
|
||||
internal async Task<dynamic> GetPictureSettings()
|
||||
{
|
||||
//var keys = new[] { "backlight", "brightness", "contrast", "color", "pictureMode", "colorGamut", "dynamicContrast", "peakBrightness", "smoothGradation", "energySaving", "motionProOLED" };
|
||||
//var keys = new[] { "backlight", "brightness", "contrast", "color" };
|
||||
|
||||
return await _lgTvApi.GetSystemSettings2("picture");
|
||||
}
|
||||
|
||||
private bool WakeAction(Dictionary<string, object> parameters)
|
||||
{
|
||||
return Wake();
|
||||
}
|
||||
|
||||
private bool TurnScreenOffAction(Dictionary<string, object> parameters)
|
||||
{
|
||||
var task = _lgTvApi.TurnScreenOff();
|
||||
Utils.WaitForTask(task);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool TurnScreenOnAction(Dictionary<string, object> parameters)
|
||||
{
|
||||
var task = _lgTvApi.TurnScreenOn();
|
||||
Utils.WaitForTask(task);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool GenericPictureAction(Dictionary<string, object> parameters)
|
||||
{
|
||||
var settingName = parameters["name"].ToString();
|
||||
var stringValues = parameters["value"] as string[];
|
||||
var category = parameters["category"].ToString();
|
||||
object value = stringValues[0];
|
||||
if (stringValues.Length > 1)
|
||||
{
|
||||
value = stringValues.Select(s => int.Parse(s)).ToArray();
|
||||
}
|
||||
var task = _lgTvApi.SetSystemSettings(settingName, value, category);
|
||||
Utils.WaitForTask(task);
|
||||
|
||||
UpdateCurrentValueOfAction(settingName, value.ToString());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool GenericDeviceConfigAction(Dictionary<string, object> parameters)
|
||||
{
|
||||
var id = parameters["name"].ToString().Replace("_icon", string.Empty);
|
||||
var stringValues = parameters["value"] as string[];
|
||||
var value = stringValues[0];
|
||||
|
||||
var description = Utils.GetDescriptionByEnumName<HdmiIcon>(value);
|
||||
|
||||
var task = _lgTvApi.SetDeviceConfig(id, value, description);
|
||||
Utils.WaitForTask(task);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private void UpdateCurrentValueOfAction(string settingName, string value)
|
||||
{
|
||||
if (settingName != "backlight" && settingName != "contrast" && settingName != "brightness" && settingName != "color")
|
||||
{
|
||||
var action = _invokableActions.FirstOrDefault(a => a.Name == settingName);
|
||||
if (action != null)
|
||||
{
|
||||
if (action.EnumType != null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var enumValue = Enum.Parse(action.EnumType, value);
|
||||
var intEnum = (int)enumValue;
|
||||
action.CurrentValue = intEnum;
|
||||
}
|
||||
catch (Exception) { }
|
||||
}
|
||||
else
|
||||
{
|
||||
action.CurrentValue = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+139
@@ -0,0 +1,139 @@
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
partial class LgGameBar
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Windows Form Designer generated code
|
||||
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this.components = new System.ComponentModel.Container();
|
||||
this.flowPanel = new System.Windows.Forms.FlowLayoutPanel();
|
||||
this.btnClose = new System.Windows.Forms.Button();
|
||||
this.lblTvName = new System.Windows.Forms.Label();
|
||||
this.tmrHide = new System.Windows.Forms.Timer(this.components);
|
||||
this.lblProcessName = new System.Windows.Forms.Label();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// flowPanel
|
||||
//
|
||||
this.flowPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
|
||||
| System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.flowPanel.Location = new System.Drawing.Point(14, 47);
|
||||
this.flowPanel.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
|
||||
this.flowPanel.Name = "flowPanel";
|
||||
this.flowPanel.Size = new System.Drawing.Size(270, 325);
|
||||
this.flowPanel.TabIndex = 0;
|
||||
this.flowPanel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.RemoteControlForm_MouseDown);
|
||||
this.flowPanel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.flowPanel_MouseMove);
|
||||
this.flowPanel.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.flowPanel_PreviewKeyDown);
|
||||
//
|
||||
// btnClose
|
||||
//
|
||||
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.btnClose.FlatAppearance.BorderColor = System.Drawing.Color.DarkGray;
|
||||
this.btnClose.FlatAppearance.BorderSize = 0;
|
||||
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
|
||||
this.btnClose.ForeColor = System.Drawing.Color.White;
|
||||
this.btnClose.Location = new System.Drawing.Point(280, 0);
|
||||
this.btnClose.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
|
||||
this.btnClose.Name = "btnClose";
|
||||
this.btnClose.Size = new System.Drawing.Size(16, 27);
|
||||
this.btnClose.TabIndex = 1;
|
||||
this.btnClose.TabStop = false;
|
||||
this.btnClose.Text = "x";
|
||||
this.btnClose.UseVisualStyleBackColor = true;
|
||||
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
|
||||
//
|
||||
// lblTvName
|
||||
//
|
||||
this.lblTvName.AutoSize = true;
|
||||
this.lblTvName.ForeColor = System.Drawing.Color.White;
|
||||
this.lblTvName.Location = new System.Drawing.Point(14, 0);
|
||||
this.lblTvName.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
|
||||
this.lblTvName.Name = "lblTvName";
|
||||
this.lblTvName.Size = new System.Drawing.Size(25, 15);
|
||||
this.lblTvName.TabIndex = 0;
|
||||
this.lblTvName.Text = " ";
|
||||
//
|
||||
// tmrHide
|
||||
//
|
||||
this.tmrHide.Interval = 5000;
|
||||
this.tmrHide.Tick += new System.EventHandler(this.tmrHide_Tick);
|
||||
//
|
||||
// lblProcessName
|
||||
//
|
||||
this.lblProcessName.AutoSize = true;
|
||||
this.lblProcessName.ForeColor = System.Drawing.Color.White;
|
||||
this.lblProcessName.Location = new System.Drawing.Point(14, 23);
|
||||
this.lblProcessName.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0);
|
||||
this.lblProcessName.Name = "lblProcessName";
|
||||
this.lblProcessName.Size = new System.Drawing.Size(25, 15);
|
||||
this.lblProcessName.TabIndex = 2;
|
||||
this.lblProcessName.Text = " ";
|
||||
//
|
||||
// LgGameBar
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.BackColor = System.Drawing.Color.Black;
|
||||
this.ClientSize = new System.Drawing.Size(298, 387);
|
||||
this.Controls.Add(this.lblProcessName);
|
||||
this.Controls.Add(this.lblTvName);
|
||||
this.Controls.Add(this.btnClose);
|
||||
this.Controls.Add(this.flowPanel);
|
||||
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
|
||||
this.KeyPreview = true;
|
||||
this.Margin = new System.Windows.Forms.Padding(4, 3, 4, 3);
|
||||
this.MaximizeBox = false;
|
||||
this.MinimizeBox = false;
|
||||
this.Name = "LgGameBar";
|
||||
this.Opacity = 0.7D;
|
||||
this.StartPosition = System.Windows.Forms.FormStartPosition.Manual;
|
||||
this.Text = "RemoteControlForm";
|
||||
this.TopMost = true;
|
||||
this.Activated += new System.EventHandler(this.LgGameBar_Activated);
|
||||
this.Deactivate += new System.EventHandler(this.LgGameBar_Deactivate);
|
||||
this.Load += new System.EventHandler(this.RemoteControlForm_Load);
|
||||
this.Shown += new System.EventHandler(this.RemoteControlForm_Shown);
|
||||
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.RemoteControlForm_KeyDown);
|
||||
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.RemoteControlForm_KeyUp);
|
||||
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.RemoteControlForm_MouseDown);
|
||||
this.Move += new System.EventHandler(this.LgGameBar_Move);
|
||||
this.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.RemoteControlForm_PreviewKeyDown);
|
||||
this.ResumeLayout(false);
|
||||
this.PerformLayout();
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private System.Windows.Forms.FlowLayoutPanel flowPanel;
|
||||
private System.Windows.Forms.Button btnClose;
|
||||
private System.Windows.Forms.Label lblTvName;
|
||||
private System.Windows.Forms.Timer tmrHide;
|
||||
private System.Windows.Forms.Label lblProcessName;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,322 @@
|
||||
using NWin32;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
partial class LgGameBar : Form
|
||||
{
|
||||
private class TbSetting
|
||||
{
|
||||
public TrackBar TrackBar { get; set; }
|
||||
public string Name { get; set; }
|
||||
public Type EnumType { get; set; }
|
||||
public string PropertyName { get; set; }
|
||||
}
|
||||
|
||||
private LgService _lgService;
|
||||
private LgDevice _lgDevice;
|
||||
private ToolTip _toolTip;
|
||||
private bool _settingChanged = false;
|
||||
private List<TrackBar> _trackBars = new List<TrackBar>();
|
||||
private List<string> _lastActions = new List<string>();
|
||||
|
||||
public LgGameBar(LgService lgService)
|
||||
{
|
||||
_lgService = lgService;
|
||||
|
||||
_lgDevice = _lgService.SelectedDevice;
|
||||
|
||||
_lgDevice.PictureSettingsChangedEvent += LgDevice_PictureSettingsChangedEvent;
|
||||
|
||||
InitializeComponent();
|
||||
|
||||
_toolTip = new ToolTip();
|
||||
}
|
||||
|
||||
private void GenerateComponents()
|
||||
{
|
||||
var actions = _lgDevice.GetActionsForGameBar();
|
||||
var actionNames = actions.Select(a => a.Name).ToList();
|
||||
|
||||
if (_lastActions.Count == actions.Count && _lastActions.All(a => actionNames.Contains(a))) {
|
||||
return;
|
||||
}
|
||||
|
||||
flowPanel.Controls.Clear();
|
||||
_trackBars.Clear();
|
||||
|
||||
foreach (var action in actions)
|
||||
{
|
||||
CreateGroup(action.Title, action.Name, (int)action.MinValue, (int)action.MaxValue, action.EnumType);
|
||||
}
|
||||
|
||||
_lastActions.Clear();
|
||||
_lastActions.AddRange(actionNames);
|
||||
|
||||
Width = 28 + (_trackBars.Count() * 56);
|
||||
}
|
||||
|
||||
private TrackBar CreateGroup(string title, string settingName = null, int min = 0, int max = 100, Type enumType = null)
|
||||
{
|
||||
if (settingName == null)
|
||||
{
|
||||
settingName = title.ToLowerInvariant();
|
||||
}
|
||||
|
||||
var panel = new Panel();
|
||||
panel.Width = 50;
|
||||
panel.Height = flowPanel.Height;
|
||||
var label = new Label();
|
||||
label.Text = title;
|
||||
label.ForeColor = Color.White;
|
||||
label.Parent = panel;
|
||||
|
||||
if (min == 0 && max == 0 && enumType != null)
|
||||
{
|
||||
max = Enum.GetValues(enumType).Length - 1;
|
||||
}
|
||||
|
||||
var trackBar = CreateTrackBar(min, max);
|
||||
trackBar.Top = label.Height;
|
||||
trackBar.Height = panel.Height - trackBar.Top - 4;
|
||||
trackBar.Parent = panel;
|
||||
trackBar.Scroll += tbTrackBar_Scroll;
|
||||
var margin = trackBar.Margin;
|
||||
margin.Top = 0;
|
||||
margin.Bottom = 0;
|
||||
trackBar.Margin = margin;
|
||||
trackBar.ValueChanged += TrackBar_ValueChanged;
|
||||
|
||||
var setting = new TbSetting
|
||||
{
|
||||
TrackBar = trackBar,
|
||||
Name = settingName,
|
||||
EnumType = enumType,
|
||||
PropertyName = title
|
||||
};
|
||||
|
||||
trackBar.Tag = setting;
|
||||
|
||||
panel.Parent = flowPanel;
|
||||
|
||||
_trackBars.Add(trackBar);
|
||||
|
||||
return trackBar;
|
||||
}
|
||||
|
||||
private void TrackBar_ValueChanged(object sender, EventArgs e)
|
||||
{
|
||||
//var trackBar = sender as TrackBar;
|
||||
|
||||
//if (_toolTip != null)
|
||||
//{
|
||||
// _toolTip.SetToolTip(trackBar, trackBar.Value.ToString());
|
||||
//}
|
||||
}
|
||||
|
||||
private TrackBar CreateTrackBar(int min, int max)
|
||||
{
|
||||
var trackBar = new TrackBar();
|
||||
trackBar.BackColor = Color.Black;
|
||||
trackBar.Orientation = Orientation.Vertical;
|
||||
trackBar.TickFrequency = (max >= 50) ? 5 : 1;
|
||||
trackBar.TickStyle = TickStyle.Both;
|
||||
trackBar.Minimum = min;
|
||||
trackBar.Maximum = max;
|
||||
|
||||
return trackBar;
|
||||
}
|
||||
|
||||
private void LgDevice_PictureSettingsChangedEvent(object sender, EventArgs e)
|
||||
{
|
||||
if (_settingChanged)
|
||||
{
|
||||
_settingChanged = false;
|
||||
return;
|
||||
}
|
||||
BeginInvoke(new Action(UpdateValues));
|
||||
}
|
||||
|
||||
private void UpdateValues()
|
||||
{
|
||||
var dynType = _lgDevice.PictureSettings.GetType();
|
||||
var actions = _lgDevice.GetInvokableActions();
|
||||
foreach (var trackbar in _trackBars.Where(t => !t.Focused))
|
||||
{
|
||||
var setting = (TbSetting)trackbar.Tag;
|
||||
|
||||
if (setting.PropertyName == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var prop = dynType.GetProperty(setting.PropertyName);
|
||||
|
||||
if (prop != null)
|
||||
{
|
||||
var value = prop.GetValue(_lgDevice.PictureSettings);
|
||||
|
||||
if (value is int intValue)
|
||||
{
|
||||
trackbar.Value = intValue;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var action = actions.FirstOrDefault(a => a.Name == setting.Name);
|
||||
if (action != null)
|
||||
{
|
||||
trackbar.Value = action.CurrentValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlForm_Load(object sender, EventArgs e)
|
||||
{
|
||||
Left = _lgService.Config.GameBarLeft;
|
||||
Top = _lgService.Config.GameBarTop;
|
||||
}
|
||||
|
||||
private void ButtonClick(object sender, EventArgs e)
|
||||
{
|
||||
if (e is MouseEventArgs)
|
||||
{
|
||||
var preset = (LgPreset)(sender as Button).Tag;
|
||||
|
||||
var _ = _lgService.ApplyPreset(preset);
|
||||
}
|
||||
}
|
||||
|
||||
private void btnClose_Click(object sender, EventArgs e)
|
||||
{
|
||||
Hide();
|
||||
}
|
||||
|
||||
private void RemoteControlForm_MouseDown(object sender, MouseEventArgs e)
|
||||
{
|
||||
if (e.Button == MouseButtons.Left)
|
||||
{
|
||||
NativeMethods.ReleaseCapture();
|
||||
var intPtr = new UIntPtr(2);
|
||||
NativeMethods.SendMessageW(Handle, NativeConstants.WM_NCLBUTTONDOWN, intPtr, IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlForm_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
//var key = e.KeyCode;
|
||||
//HandleKey(key);
|
||||
}
|
||||
|
||||
private void flowPanel_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
|
||||
{
|
||||
//HandleKey(e.KeyCode);
|
||||
}
|
||||
|
||||
private void HandleKey(Keys key)
|
||||
{
|
||||
var cvt = new KeysConverter();
|
||||
var shortcut = (string)cvt.ConvertTo(key, typeof(string));
|
||||
}
|
||||
|
||||
private void RemoteControlForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
|
||||
{
|
||||
//HandleKey(e.KeyCode);
|
||||
}
|
||||
|
||||
private void RemoteControlForm_KeyUp(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyCode == Keys.F1)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
HandleKey(e.KeyCode);
|
||||
}
|
||||
|
||||
private void flowPanel_MouseMove(object sender, MouseEventArgs e)
|
||||
{
|
||||
ResetAutoHide();
|
||||
}
|
||||
|
||||
private void RemoteControlForm_Shown(object sender, EventArgs e)
|
||||
{
|
||||
GenerateComponents();
|
||||
UpdateInfo();
|
||||
ResetAutoHide();
|
||||
}
|
||||
|
||||
private void UpdateInfo()
|
||||
{
|
||||
lblTvName.Text = $"Device: {_lgDevice?.Name ?? "No tv selected"}";
|
||||
lblProcessName.Text = $"Current process: {_lgService.MonitorContext?.ForegroundProcess?.ProcessName ?? _lgService.MonitorContext?.LastFullScreenProcessName ?? "No full screen process"}";
|
||||
|
||||
UpdateValues();
|
||||
}
|
||||
|
||||
private void LgGameBar_Deactivate(object sender, EventArgs e)
|
||||
{
|
||||
_lgService.Config.GameBarLeft = Left;
|
||||
_lgService.Config.GameBarTop = Top;
|
||||
Hide();
|
||||
}
|
||||
|
||||
private void tmrHide_Tick(object sender, EventArgs e)
|
||||
{
|
||||
_lgService.Config.GameBarLeft = Left;
|
||||
_lgService.Config.GameBarTop = Top;
|
||||
Hide();
|
||||
}
|
||||
|
||||
private void tbTrackBar_Scroll(object sender, EventArgs e)
|
||||
{
|
||||
_settingChanged = true;
|
||||
ResetAutoHide();
|
||||
|
||||
var trackBar = sender as TrackBar;
|
||||
var setting = (TbSetting)trackBar.Tag;
|
||||
|
||||
var value = string.Empty;
|
||||
|
||||
if (setting.EnumType == null)
|
||||
{
|
||||
value = trackBar.Value.ToString();
|
||||
}
|
||||
else
|
||||
{
|
||||
var enumValue = Enum.Parse(setting.EnumType, trackBar.Value.ToString());
|
||||
value = enumValue.ToString();
|
||||
}
|
||||
|
||||
_lgDevice.SetSystemSettings(setting.Name, value).ConfigureAwait(false);
|
||||
|
||||
if (_toolTip != null)
|
||||
{
|
||||
_toolTip.Show(value, trackBar, 10, 50, 1500);
|
||||
}
|
||||
}
|
||||
|
||||
private void LgGameBar_Activated(object sender, EventArgs e)
|
||||
{
|
||||
GenerateComponents();
|
||||
UpdateInfo();
|
||||
ResetAutoHide();
|
||||
}
|
||||
|
||||
private void LgGameBar_Move(object sender, EventArgs e)
|
||||
{
|
||||
ResetAutoHide();
|
||||
}
|
||||
|
||||
private void ResetAutoHide()
|
||||
{
|
||||
tmrHide.Enabled = false;
|
||||
tmrHide.Enabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<metadata name="tmrHide.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
</root>
|
||||
@@ -1,4 +1,5 @@
|
||||
using LgTv;
|
||||
using Newtonsoft.Json;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -6,13 +7,19 @@ namespace ColorControl
|
||||
{
|
||||
class LgPreset : PresetBase
|
||||
{
|
||||
public string name { get; set; }
|
||||
public static List<LgApp> LgApps { get; set; }
|
||||
public static List<LgDevice> LgDevices { get; set; }
|
||||
public string appId { get; set; }
|
||||
public List<string> steps { get; set; }
|
||||
public string DeviceMacAddress { get; set; }
|
||||
public dynamic AppParams { get; set; }
|
||||
|
||||
public static List<LgApp> LgApps { get; set; }
|
||||
[JsonIgnore]
|
||||
public int X { get; set; }
|
||||
[JsonIgnore]
|
||||
public int Y { get; set; }
|
||||
|
||||
public LgPreset()
|
||||
public LgPreset() : base()
|
||||
{
|
||||
steps = new List<string>();
|
||||
}
|
||||
@@ -29,6 +36,17 @@ namespace ColorControl
|
||||
}
|
||||
}
|
||||
|
||||
public LgPreset(string name, string appId, IEnumerable<string> steps = null, dynamic appParams = null) : this()
|
||||
{
|
||||
this.name = name;
|
||||
this.appId = appId;
|
||||
if (steps != null)
|
||||
{
|
||||
this.steps.AddRange(steps);
|
||||
}
|
||||
AppParams = appParams;
|
||||
}
|
||||
|
||||
public LgPreset Clone()
|
||||
{
|
||||
var preset = new LgPreset(this);
|
||||
@@ -38,14 +56,37 @@ namespace ColorControl
|
||||
|
||||
public static List<string> GetColumnNames()
|
||||
{
|
||||
return new List<string>() { "Name", "App|200", "Steps|400", "Shortcut" };
|
||||
return new List<string>() { "Name", "Device|120", "App|200", "Steps|400", "Shortcut", "Trigger" };
|
||||
}
|
||||
|
||||
public List<string> GetDisplayValues()
|
||||
public override List<string> GetDisplayValues(Config config = null)
|
||||
{
|
||||
var values = new List<string>();
|
||||
|
||||
values.Add(name);
|
||||
|
||||
var deviceString = "Global";
|
||||
if (!string.IsNullOrEmpty(DeviceMacAddress))
|
||||
{
|
||||
if (LgDevices != null)
|
||||
{
|
||||
var device = LgDevices.FirstOrDefault(d => !string.IsNullOrEmpty(d.MacAddress) && d.MacAddress.Equals(DeviceMacAddress));
|
||||
if (device != null)
|
||||
{
|
||||
deviceString = device.Name;
|
||||
}
|
||||
else
|
||||
{
|
||||
deviceString = "Unknown: device not found";
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
deviceString = DeviceMacAddress;
|
||||
}
|
||||
}
|
||||
values.Add(deviceString);
|
||||
|
||||
var app = appId;
|
||||
if (LgApps != null)
|
||||
{
|
||||
@@ -59,6 +100,11 @@ namespace ColorControl
|
||||
values.Add(GetStepsDisplay());
|
||||
values.Add(shortcut);
|
||||
|
||||
if (Triggers.Any())
|
||||
{
|
||||
values.Add(Triggers.First().ToString());
|
||||
}
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
|
||||
+706
-215
File diff suppressed because it is too large.
Load diff
@@ -1,25 +1,31 @@
|
||||
namespace ColorControl
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class LgServiceConfig
|
||||
{
|
||||
public bool PowerOnAfterStartup { get; set; }
|
||||
|
||||
public bool PowerOnAfterResume { get; set; }
|
||||
|
||||
public bool PowerOffOnShutdown { get; set; }
|
||||
|
||||
public bool PowerOffOnStandby { get; set; }
|
||||
|
||||
public int PowerOnDelayAfterResume { get; set; }
|
||||
|
||||
public int PowerOnRetries { get; set; }
|
||||
public string PreferredMacAddress { get; set; }
|
||||
|
||||
public string DeviceSearchKey { get; set; }
|
||||
public List<LgDevice> Devices { get; set; }
|
||||
public bool ShowRemoteControl { get; set; }
|
||||
public bool ShowAdvancedActions { get; set; }
|
||||
public string GameBarShortcut { get; set; }
|
||||
public int GameBarTop { get; set; }
|
||||
public int GameBarLeft { get; set; }
|
||||
public int ShutdownDelay { get; set; }
|
||||
|
||||
public LgServiceConfig()
|
||||
{
|
||||
PowerOnDelayAfterResume = 5000;
|
||||
ShutdownDelay = 1000;
|
||||
DeviceSearchKey = "[LG]";
|
||||
PowerOnRetries = 10;
|
||||
Devices = new List<LgDevice>();
|
||||
GameBarTop = 100;
|
||||
GameBarLeft = 100;
|
||||
}
|
||||
}
|
||||
}
|
||||
Generated
+1658
-454
File diff suppressed because it is too large.
Load diff
+1921
-698
File diff suppressed because it is too large.
Load diff
@@ -1,64 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<root>
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
@@ -120,6 +60,12 @@
|
||||
<metadata name="mnuNvPresets.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>17, 17</value>
|
||||
</metadata>
|
||||
<metadata name="mnuAmdPresets.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>278, 17</value>
|
||||
</metadata>
|
||||
<metadata name="mnuLgExpert.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>583, 17</value>
|
||||
</metadata>
|
||||
<metadata name="mnuLgButtons.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
|
||||
<value>147, 17</value>
|
||||
</metadata>
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class MessageForms
|
||||
{
|
||||
public enum FieldType
|
||||
{
|
||||
Text,
|
||||
Numeric,
|
||||
DropDown,
|
||||
Flags
|
||||
}
|
||||
|
||||
public class FieldDefinition
|
||||
{
|
||||
public string Label { get; set; }
|
||||
public FieldType FieldType { get; set; } = FieldType.Text;
|
||||
public IEnumerable<string> Values { get; set; }
|
||||
public decimal MinValue { get; set; }
|
||||
public decimal MaxValue { get; set; }
|
||||
public object Value { get; set; }
|
||||
}
|
||||
|
||||
public static Form MainForm;
|
||||
|
||||
public static void WarningOk(string text)
|
||||
{
|
||||
MessageBox.Show(text, MainForm?.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning);
|
||||
}
|
||||
|
||||
public static void ErrorOk(string text)
|
||||
{
|
||||
MessageBox.Show(text, MainForm?.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
|
||||
}
|
||||
|
||||
public static void InfoOk(string text, string title = null, string url = null)
|
||||
{
|
||||
if (url != null)
|
||||
{
|
||||
MessageBox.Show(text, title ?? MainForm?.Text, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, 0, url);
|
||||
}
|
||||
else
|
||||
{
|
||||
MessageBox.Show(text, title ?? MainForm?.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
|
||||
}
|
||||
}
|
||||
|
||||
public static DialogResult QuestionYesNo(string text)
|
||||
{
|
||||
return MessageBox.Show(text, MainForm?.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Information);
|
||||
}
|
||||
|
||||
public static List<FieldDefinition> ShowDialog(string caption, IEnumerable<string> labels, Func<IEnumerable<FieldDefinition>, string> validateFunc = null)
|
||||
{
|
||||
var fieldDefinitions = labels.Select(l => new FieldDefinition
|
||||
{
|
||||
Label = l
|
||||
}).ToList();
|
||||
|
||||
return ShowDialog(caption, fieldDefinitions, validateFunc);
|
||||
}
|
||||
|
||||
public static List<FieldDefinition> ShowDialog(string caption, IEnumerable<FieldDefinition> fields, Func<IEnumerable<FieldDefinition>, string> validateFunc = null)
|
||||
{
|
||||
var values = new List<FieldDefinition>();
|
||||
|
||||
var prompt = new Form()
|
||||
{
|
||||
Width = 500,
|
||||
Height = 90 + (fields.Count() * 55),
|
||||
FormBorderStyle = FormBorderStyle.FixedDialog,
|
||||
Text = caption,
|
||||
StartPosition = FormStartPosition.CenterScreen
|
||||
};
|
||||
|
||||
var top = 10;
|
||||
var boxes = new List<Control>();
|
||||
|
||||
foreach (var field in fields)
|
||||
{
|
||||
var label = field.Label;
|
||||
var textLabel = new Label() { Left = 40, Top = top, Text = label, AutoSize = true };
|
||||
top += 25;
|
||||
prompt.Controls.Add(textLabel);
|
||||
|
||||
Control control;
|
||||
|
||||
switch(field.FieldType)
|
||||
{
|
||||
case FieldType.Text:
|
||||
var textBox = new MaskedTextBox() { Left = 40, Top = top, Width = 400 };
|
||||
|
||||
if (label.Contains("Ip-address"))
|
||||
{
|
||||
//textBox.Mask = "990.990.990.990";
|
||||
//textBox.ValidatingType = typeof(System.Net.IPAddress);
|
||||
textBox.Culture = CultureInfo.InvariantCulture;
|
||||
}
|
||||
else if (label.Contains("MAC-address"))
|
||||
{
|
||||
textBox.Mask = "AA-AA-AA-AA-AA-AA";
|
||||
textBox.Culture = CultureInfo.InvariantCulture;
|
||||
}
|
||||
|
||||
control = textBox;
|
||||
break;
|
||||
|
||||
case FieldType.Numeric:
|
||||
var numericEdit = new NumericUpDown() { Left = 40, Top = top, Width = 400 };
|
||||
|
||||
if (field.MinValue != field.MaxValue)
|
||||
{
|
||||
numericEdit.Minimum = field.MinValue;
|
||||
numericEdit.Maximum = field.MaxValue;
|
||||
}
|
||||
|
||||
control = numericEdit;
|
||||
break;
|
||||
|
||||
case FieldType.DropDown:
|
||||
var comboBox = new ComboBox
|
||||
{
|
||||
Left = 40,
|
||||
Top = top,
|
||||
Width = 400,
|
||||
DropDownStyle = ComboBoxStyle.DropDownList
|
||||
};
|
||||
|
||||
if (field.Values != null && field.Values.Any())
|
||||
{
|
||||
comboBox.Items.AddRange(field.Values.ToArray());
|
||||
comboBox.SelectedIndex = 0;
|
||||
}
|
||||
|
||||
control = comboBox;
|
||||
break;
|
||||
|
||||
case FieldType.Flags:
|
||||
var checkedListBox = new CheckedListBox
|
||||
{
|
||||
Left = 40,
|
||||
Top = top,
|
||||
Width = 200,
|
||||
Height = 100
|
||||
};
|
||||
|
||||
top += 80;
|
||||
prompt.Height += 80;
|
||||
|
||||
if (field.Values != null && field.Values.Any())
|
||||
{
|
||||
var compoundValue = (int)field.Value;
|
||||
var enumValue = 1;
|
||||
foreach (var value in field.Values)
|
||||
{
|
||||
var isChecked = (compoundValue & enumValue) == enumValue;
|
||||
|
||||
checkedListBox.Items.Add(value, isChecked);
|
||||
|
||||
enumValue *= 2;
|
||||
}
|
||||
}
|
||||
|
||||
control = checkedListBox;
|
||||
break;
|
||||
|
||||
default:
|
||||
continue;
|
||||
}
|
||||
|
||||
top += 30;
|
||||
prompt.Controls.Add(control);
|
||||
boxes.Add(control);
|
||||
control.Tag = field;
|
||||
}
|
||||
|
||||
var confirmation = new Button() { Text = "OK", Left = 365, Width = 75, Top = prompt.ClientRectangle.Height - 30 };
|
||||
confirmation.Click += (sender, e) =>
|
||||
{
|
||||
foreach (var box in boxes)
|
||||
{
|
||||
var field = (FieldDefinition)box.Tag;
|
||||
|
||||
switch (field.FieldType)
|
||||
{
|
||||
case FieldType.Flags:
|
||||
var checkedListBox = (CheckedListBox)box;
|
||||
|
||||
var compoundValue = 0;
|
||||
var enumValue = 1;
|
||||
for (var i = 0; i < checkedListBox.Items.Count; i++)
|
||||
{
|
||||
compoundValue += checkedListBox.GetItemChecked(i) ? enumValue : 0;
|
||||
enumValue *= 2;
|
||||
}
|
||||
|
||||
field.Value = compoundValue;
|
||||
break;
|
||||
default:
|
||||
field.Value = box.Text.Trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (validateFunc != null)
|
||||
{
|
||||
var message = validateFunc(fields);
|
||||
|
||||
if (!string.IsNullOrEmpty(message))
|
||||
{
|
||||
WarningOk(message);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
values.AddRange(fields);
|
||||
|
||||
prompt.Close();
|
||||
};
|
||||
prompt.Controls.Add(confirmation);
|
||||
prompt.AcceptButton = confirmation;
|
||||
|
||||
prompt.ShowDialog(MainForm);
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
public static Form ShowProgress(string caption)
|
||||
{
|
||||
var prompt = new Form()
|
||||
{
|
||||
Width = 300,
|
||||
Height = 100,
|
||||
FormBorderStyle = FormBorderStyle.FixedToolWindow,
|
||||
Text = caption,
|
||||
StartPosition = FormStartPosition.CenterScreen,
|
||||
ControlBox = false
|
||||
};
|
||||
var textLabel = new Label() { Left = 20, Top = 25, Text = caption, AutoSize = true };
|
||||
prompt.Controls.Add(textLabel);
|
||||
|
||||
prompt.Show(MainForm);
|
||||
|
||||
return prompt;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace NonInvasiveKeyboardHookLibrary
|
||||
{
|
||||
/// <summary>
|
||||
/// A struct to represent a keybind (key + modifiers)
|
||||
/// When the keybind struct is compared to another keybind struct, the equality is based on the
|
||||
/// modifiers and the virtual key code.
|
||||
/// </summary>
|
||||
internal class KeybindStruct : IEquatable<KeybindStruct>
|
||||
{
|
||||
public readonly int VirtualKeyCode;
|
||||
public readonly List<ModifierKeys> Modifiers;
|
||||
public readonly Guid? Identifier;
|
||||
|
||||
public KeybindStruct(IEnumerable<ModifierKeys> modifiers, int virtualKeyCode, Guid? identifier = null)
|
||||
{
|
||||
this.VirtualKeyCode = virtualKeyCode;
|
||||
this.Modifiers = new List<ModifierKeys>(modifiers);
|
||||
this.Identifier = identifier;
|
||||
}
|
||||
|
||||
public bool Equals(KeybindStruct other)
|
||||
{
|
||||
if (other == null)
|
||||
return false;
|
||||
|
||||
if (this.VirtualKeyCode != other.VirtualKeyCode)
|
||||
return false;
|
||||
|
||||
if (this.Modifiers.Count != other.Modifiers.Count)
|
||||
return false;
|
||||
|
||||
foreach (var modifier in this.Modifiers)
|
||||
{
|
||||
if (!other.Modifiers.Contains(modifier))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
if (ReferenceEquals(null, obj)) return false;
|
||||
if (ReferenceEquals(this, obj)) return true;
|
||||
if (obj.GetType() != this.GetType()) return false;
|
||||
|
||||
return Equals((KeybindStruct) obj);
|
||||
}
|
||||
|
||||
public override int GetHashCode()
|
||||
{
|
||||
var hash = 13;
|
||||
hash = (hash * 7) + VirtualKeyCode.GetHashCode();
|
||||
|
||||
// Sum the modifiers separately, so that their order does not affect the final hash
|
||||
var modifiersHashSum = 0;
|
||||
foreach (var modifier in this.Modifiers)
|
||||
{
|
||||
modifiersHashSum += modifier.GetHashCode();
|
||||
}
|
||||
|
||||
hash = (hash * 7) + modifiersHashSum;
|
||||
|
||||
return hash;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Threading;
|
||||
|
||||
namespace NonInvasiveKeyboardHookLibrary
|
||||
{
|
||||
internal struct KeyboardParams
|
||||
{
|
||||
public IntPtr wParam;
|
||||
public int vkCode;
|
||||
|
||||
public KeyboardParams(IntPtr wParam, int vkCode)
|
||||
{
|
||||
this.wParam = wParam;
|
||||
this.vkCode = vkCode;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A hotkey manager that uses a low-level global keyboard hook, but eventually only fires events for
|
||||
/// pre-registered hotkeys, i.e. not invading a user's privacy.
|
||||
/// </summary>
|
||||
public class KeyboardHookManager
|
||||
{
|
||||
#region Private Attributes
|
||||
/// <summary>
|
||||
/// Keeps track of all registered hotkeys
|
||||
/// </summary>
|
||||
private readonly Dictionary<KeybindStruct, Action> _registeredCallbacks;
|
||||
/// <summary>
|
||||
/// Keeps track of modifier keys that are held down
|
||||
/// </summary>
|
||||
private readonly HashSet<ModifierKeys> _downModifierKeys;
|
||||
/// <summary>
|
||||
/// Keeps track of all keys that are held down to prevent firing callbacks
|
||||
/// more than once for a single keypress
|
||||
/// </summary>
|
||||
private readonly HashSet<int> _downKeys;
|
||||
private readonly object _modifiersLock = new object();
|
||||
private LowLevelKeyboardProc _hook;
|
||||
private bool _isStarted;
|
||||
#endregion
|
||||
|
||||
#region Constructors
|
||||
/// <summary>
|
||||
/// Instantiates an empty keyboard hook manager.
|
||||
/// It is best practice to keep a single instance per process.
|
||||
/// Start() must be called to start the low-level keyboard hook manager
|
||||
/// </summary>
|
||||
public KeyboardHookManager()
|
||||
{
|
||||
this._registeredCallbacks = new Dictionary<KeybindStruct, Action>();
|
||||
this._downModifierKeys = new HashSet<ModifierKeys>();
|
||||
this._downKeys = new HashSet<int>();
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Public API
|
||||
/// <summary>
|
||||
/// Starts the low-level keyboard hook.
|
||||
/// Hotkeys can be registered regardless of the low-level keyboard hook's state, but their callbacks
|
||||
/// will only ever be invoked if the low-level keyboard hook is running and intercepting keys.
|
||||
/// </summary>
|
||||
public void Start()
|
||||
{
|
||||
if (this._isStarted) return;
|
||||
|
||||
this._hook = this.HookCallback;
|
||||
_hookId = SetHook(this._hook);
|
||||
this._isStarted = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pauses the low-level keyboard hook (without unregistering the existing hotkeys)
|
||||
/// </summary>
|
||||
public void Stop()
|
||||
{
|
||||
if (this._isStarted)
|
||||
{
|
||||
UnhookWindowsHookEx(_hookId);
|
||||
this._isStarted = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a hotkey.
|
||||
/// </summary>
|
||||
/// <param name="virtualKeyCode">The virtual key code of the hotkey</param>
|
||||
/// <param name="action">The callback action to invoke when this hotkey is pressed</param>
|
||||
/// <exception cref="HotkeyAlreadyRegisteredException">Thrown when the given key is already mapped to a callback</exception>
|
||||
/// /// <returns>Unique identifier of this hotkey, which can be used to remove it later</returns>
|
||||
public Guid RegisterHotkey(int virtualKeyCode, Action action)
|
||||
{
|
||||
return this.RegisterHotkey(new ModifierKeys[0], virtualKeyCode, action);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new key combination with one or more modifiers
|
||||
/// </summary>
|
||||
/// <param name="modifiers">Modifiers that must be held while hitting the key. Multiple modifiers can be provided using the flags bitwise OR operation</param>
|
||||
/// <param name="virtualKeyCode">The virtual key code of the standard key</param>
|
||||
/// <param name="action">The callback action to invoke when this combination is pressed</param>
|
||||
/// <exception cref="HotkeyAlreadyRegisteredException">Thrown when the given key combination is already mapped to a callback</exception>
|
||||
/// <returns>Unique identifier of this hotkey, which can be used to remove it later</returns>
|
||||
public Guid RegisterHotkey(ModifierKeys modifiers, int virtualKeyCode, Action action)
|
||||
{
|
||||
var allModifiers = Enum.GetValues(typeof(ModifierKeys)).Cast<ModifierKeys>().ToArray();
|
||||
|
||||
// Get the modifiers that were chained with bitwise OR operation as an array of modifiers
|
||||
var selectedModifiers = allModifiers.Where(modifier => modifiers.HasFlag(modifier)).ToArray();
|
||||
|
||||
return RegisterHotkey(selectedModifiers, virtualKeyCode, action);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Registers a new key combination.
|
||||
/// </summary>
|
||||
/// <param name="modifiers">Modifiers that must be held while hitting the key</param>
|
||||
/// <param name="virtualKeyCode">The virtual key code of the standard key</param>
|
||||
/// <param name="action">The callback action to invoke when this combination is pressed</param>
|
||||
/// <exception cref="HotkeyAlreadyRegisteredException">Thrown when the given key combination is already mapped to a callback</exception>
|
||||
/// <returns>Unique identifier of this hotkey, which can be used to remove it later</returns>
|
||||
public Guid RegisterHotkey(ModifierKeys[] modifiers, int virtualKeyCode, Action action)
|
||||
{
|
||||
var keybindIdentity = Guid.NewGuid();
|
||||
var keybind = new KeybindStruct(modifiers, virtualKeyCode, keybindIdentity);
|
||||
if (this._registeredCallbacks.ContainsKey(keybind))
|
||||
{
|
||||
throw new HotkeyAlreadyRegisteredException();
|
||||
}
|
||||
|
||||
this._registeredCallbacks[keybind] = action;
|
||||
return keybindIdentity;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters all hotkeys (the low-level keyboard hook continues running)
|
||||
/// </summary>
|
||||
public void UnregisterAll()
|
||||
{
|
||||
this._registeredCallbacks.Clear();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters a specific single-key hotkey
|
||||
/// </summary>
|
||||
/// <param name="virtualKeyCode">Virtual key code of the unregistered key</param>
|
||||
/// <exception cref="HotkeyNotRegisteredException">Thrown when the given key combination is not registered</exception>
|
||||
public void UnregisterHotkey(int virtualKeyCode)
|
||||
{
|
||||
this.UnregisterHotkey(new ModifierKeys[0], virtualKeyCode);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters a specific key combination
|
||||
/// </summary>
|
||||
/// <param name="modifiers">The modifiers of the combination</param>
|
||||
/// <param name="virtualKeyCode">The key of the combination</param>
|
||||
/// <exception cref="HotkeyNotRegisteredException">Thrown when the given key combination is not registered</exception>
|
||||
public void UnregisterHotkey(ModifierKeys[] modifiers, int virtualKeyCode)
|
||||
{
|
||||
var keybind = new KeybindStruct(modifiers, virtualKeyCode);
|
||||
|
||||
if (!this._registeredCallbacks.Remove(keybind))
|
||||
{
|
||||
throw new HotkeyNotRegisteredException();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Unregisters a specific key by its unique identifier
|
||||
/// </summary>
|
||||
/// <param name="keybindIdentity">Keybind GUID, as returned by RegisterHotkey</param>
|
||||
public void UnregisterHotkey(Guid keybindIdentity)
|
||||
{
|
||||
var keybindToRemove = this._registeredCallbacks.Keys.FirstOrDefault(keybind =>
|
||||
keybind.Identifier.HasValue && keybind.Identifier.Value.Equals(keybindIdentity));
|
||||
|
||||
if (keybindToRemove == null || !this._registeredCallbacks.Remove(keybindToRemove))
|
||||
{
|
||||
throw new HotkeyNotRegisteredException();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Private methods
|
||||
private void HandleKeyPress(int virtualKeyCode)
|
||||
{
|
||||
var currentKey = new KeybindStruct(this._downModifierKeys, virtualKeyCode);
|
||||
|
||||
if (!this._registeredCallbacks.ContainsKey(currentKey))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._registeredCallbacks.TryGetValue(currentKey, out var callback))
|
||||
{
|
||||
callback.Invoke();
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region Low level keyboard hook
|
||||
// Source: https://blogs.msdn.microsoft.com/toub/2006/05/03/low-level-keyboard-hook-in-c/
|
||||
private const int WH_KEYBOARD_LL = 13;
|
||||
private const int WM_KEYDOWN = 0x0100;
|
||||
private const int WM_KEYUP = 0x0101;
|
||||
private const int WM_SYSKEYDOWN = 0x0104;
|
||||
private const int WM_SYSKEYUP = 0x0105;
|
||||
|
||||
private static IntPtr _hookId = IntPtr.Zero;
|
||||
|
||||
private static IntPtr SetHook(LowLevelKeyboardProc proc)
|
||||
{
|
||||
var userLibrary = LoadLibrary("User32");
|
||||
|
||||
return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
|
||||
userLibrary, 0);
|
||||
}
|
||||
|
||||
private IntPtr HookCallback(int nCode, IntPtr wParam, IntPtr lParam)
|
||||
{
|
||||
if (nCode >= 0)
|
||||
{
|
||||
var vkCode = Marshal.ReadInt32(lParam);
|
||||
|
||||
// Debug.WriteLine("Starting");
|
||||
// To prevent slowing keyboard input down, we use handle keyboard inputs in a separate thread
|
||||
ThreadPool.QueueUserWorkItem(this.HandleSingleKeyboardInput, new KeyboardParams(wParam, vkCode));
|
||||
// Debug.WriteLine("Ending");
|
||||
}
|
||||
|
||||
return CallNextHookEx(_hookId, nCode, wParam, lParam);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handles a keyboard event based on the KeyboardParams it receives
|
||||
/// </summary>
|
||||
/// <param name="keyboardParamsObj">KeyboardParams struct (object type to comply with QueueUserWorkItem)</param>
|
||||
private void HandleSingleKeyboardInput(object keyboardParamsObj)
|
||||
{
|
||||
var keyboardParams = (KeyboardParams)keyboardParamsObj;
|
||||
var wParam = keyboardParams.wParam;
|
||||
var vkCode = keyboardParams.vkCode;
|
||||
|
||||
var modifierKey = ModifierKeysUtilities.GetModifierKeyFromCode(vkCode);
|
||||
|
||||
// If the keyboard event is a KeyDown event (i.e. key pressed)
|
||||
if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
|
||||
{
|
||||
// In this case, we only care about modifier keys
|
||||
if (modifierKey != null)
|
||||
{
|
||||
lock (this._modifiersLock)
|
||||
{
|
||||
this._downModifierKeys.Add(modifierKey.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Trigger callbacks that are registered for this key, but only once per key press
|
||||
if (!this._downKeys.Contains(vkCode))
|
||||
{
|
||||
this.HandleKeyPress(vkCode);
|
||||
this._downKeys.Add(vkCode);
|
||||
}
|
||||
}
|
||||
|
||||
// If the keyboard event is a KeyUp event (i.e. key released)
|
||||
if (wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
|
||||
{
|
||||
// If the released key is a modifier key, remove it from the HashSet of modifier keys
|
||||
if (modifierKey != null)
|
||||
{
|
||||
lock (this._modifiersLock)
|
||||
{
|
||||
this._downModifierKeys.Remove(modifierKey.Value);
|
||||
}
|
||||
}
|
||||
|
||||
this._downKeys.Remove(vkCode);
|
||||
}
|
||||
}
|
||||
|
||||
private delegate IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
private static extern IntPtr SetWindowsHookEx(int idHook,
|
||||
LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
private static extern bool UnhookWindowsHookEx(IntPtr hhk);
|
||||
|
||||
|
||||
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
|
||||
private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
|
||||
IntPtr wParam, IntPtr lParam);
|
||||
|
||||
/// <summary>
|
||||
/// Loads the library.
|
||||
/// </summary>
|
||||
/// <param name="lpFileName">Name of the library</param>
|
||||
/// <returns>A handle to the library</returns>
|
||||
[DllImport("kernel32.dll")]
|
||||
private static extern IntPtr LoadLibrary(string lpFileName);
|
||||
#endregion
|
||||
}
|
||||
|
||||
#region Exceptions
|
||||
public class NonInvasiveKeyboardHookException : Exception
|
||||
{
|
||||
}
|
||||
|
||||
public class HotkeyAlreadyRegisteredException : NonInvasiveKeyboardHookException
|
||||
{
|
||||
}
|
||||
|
||||
public class HotkeyNotRegisteredException : NonInvasiveKeyboardHookException
|
||||
{
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
using System;
|
||||
|
||||
namespace NonInvasiveKeyboardHookLibrary
|
||||
{
|
||||
[Flags]
|
||||
public enum ModifierKeys
|
||||
{
|
||||
Alt = 1,
|
||||
Control = 2,
|
||||
Shift = 4,
|
||||
WindowsKey = 8,
|
||||
}
|
||||
|
||||
public static class ModifierKeysUtilities
|
||||
{
|
||||
public static ModifierKeys? GetModifierKeyFromCode(int keyCode)
|
||||
{
|
||||
switch (keyCode)
|
||||
{
|
||||
case 0xA0:
|
||||
case 0xA1:
|
||||
case 0x10:
|
||||
return ModifierKeys.Shift;
|
||||
|
||||
case 0xA2:
|
||||
case 0xA3:
|
||||
case 0x11:
|
||||
return ModifierKeys.Control;
|
||||
|
||||
case 0x12:
|
||||
case 0xA4:
|
||||
case 0xA5:
|
||||
return ModifierKeys.Alt;
|
||||
|
||||
case 0x5B:
|
||||
case 0x5C:
|
||||
return ModifierKeys.WindowsKey;
|
||||
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using NvAPIWrapper.Display;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class NvDisplayInfo
|
||||
{
|
||||
public Display Display { get; }
|
||||
|
||||
public List<string> Values { get; }
|
||||
|
||||
public string InfoLine { get; }
|
||||
|
||||
public NvDisplayInfo(Display display, List<string> values, string infoLine)
|
||||
{
|
||||
Display = display;
|
||||
Values = values;
|
||||
InfoLine = infoLine;
|
||||
}
|
||||
}
|
||||
}
|
||||
+65
-28
@@ -19,8 +19,10 @@ namespace ColorControl
|
||||
public uint refreshRate { get; set; }
|
||||
public bool primaryDisplay { get; set; }
|
||||
public string displayName { get; set; }
|
||||
public uint ditheringBits { get; set; }
|
||||
public uint ditheringMode { get; set; }
|
||||
|
||||
public NvPreset()
|
||||
public NvPreset() : base()
|
||||
{
|
||||
applyColorData = true;
|
||||
applyDithering = false;
|
||||
@@ -31,6 +33,8 @@ namespace ColorControl
|
||||
applyRefreshRate = false;
|
||||
refreshRate = 60;
|
||||
primaryDisplay = true;
|
||||
ditheringBits = 1;
|
||||
ditheringMode = 4;
|
||||
}
|
||||
|
||||
public NvPreset(ColorData colorData) : this()
|
||||
@@ -47,7 +51,7 @@ namespace ColorControl
|
||||
displayName = preset.displayName;
|
||||
|
||||
var colorData = preset.colorData;
|
||||
this.colorData = new ColorData(colorData.ColorFormat, dynamicRange: colorData.DynamicRange, colorDepth: colorData.ColorDepth, colorSelectionPolicy: colorData.SelectionPolicy);
|
||||
this.colorData = new ColorData(colorData.ColorFormat, dynamicRange: colorData.DynamicRange, colorDepth: colorData.ColorDepth, colorSelectionPolicy: ColorDataSelectionPolicy.User);
|
||||
applyColorData = preset.applyColorData;
|
||||
|
||||
applyHDR = preset.applyHDR;
|
||||
@@ -69,13 +73,15 @@ namespace ColorControl
|
||||
public static string[] GetColumnNames()
|
||||
{
|
||||
//return new[] { "BPC", "Format", "Dynamic range", "Toggle HDR", "Shortcut" };
|
||||
return new[] { "Display|140", "Color settings (BPC, format, dyn. range, color space)|260", "Refresh rate|100", "Dithering", "HDR", "Shortcut" };
|
||||
return new[] { "Name", "Display|140", "Color settings (BPC, format, dyn. range, color space)|260", "Refresh rate|100", "Dithering", "HDR", "Shortcut", "Apply on startup" };
|
||||
}
|
||||
|
||||
public List<string> GetDisplayValues()
|
||||
public override List<string> GetDisplayValues(Config config = null)
|
||||
{
|
||||
var values = new List<string>();
|
||||
|
||||
values.Add(name);
|
||||
|
||||
var display = string.Format("{0}", primaryDisplay ? "Primary" : displayName);
|
||||
values.Add(display);
|
||||
|
||||
@@ -83,7 +89,10 @@ namespace ColorControl
|
||||
|
||||
values.Add(colorSettings);
|
||||
values.Add(string.Format("{0}: {1}Hz", applyRefreshRate ? "Included" : "Excluded", refreshRate));
|
||||
values.Add(string.Format("{0}: {1}", applyDithering ? "Included" : "Excluded", ditheringEnabled ? "Enabled" : "Disabled"));
|
||||
|
||||
var dithering = GetDitheringDescription();
|
||||
|
||||
values.Add(string.Format("{0}: {1}", applyDithering ? "Included" : "Excluded", dithering));
|
||||
values.Add(string.Format("{0}: {1}", applyHDR ? "Included" : "Excluded", toggleHDR ? "Toggle" : HDREnabled ? "Enabled" : "Disabled"));
|
||||
|
||||
//values.Add(colorData.ColorDepth.ToString());
|
||||
@@ -92,9 +101,23 @@ namespace ColorControl
|
||||
//values.Add(toggleHDR.ToString());
|
||||
values.Add(shortcut);
|
||||
|
||||
values.Add(string.Format("{0}", config?.NvPresetId_ApplyOnStartup == id ? "Yes" : string.Empty));
|
||||
|
||||
return values;
|
||||
}
|
||||
|
||||
public string GetDitheringDescription(string disabledText = "Disabled")
|
||||
{
|
||||
var dithering = ditheringEnabled ? string.Empty : disabledText;
|
||||
if (ditheringEnabled)
|
||||
{
|
||||
var ditherBitsDescription = ((NvDitherBits)ditheringBits).GetDescription();
|
||||
var ditherModeDescription = ((NvDitherMode)ditheringMode).GetDescription();
|
||||
dithering = string.Format("{0} {1}", ditherBitsDescription, ditherModeDescription);
|
||||
}
|
||||
return dithering;
|
||||
}
|
||||
|
||||
public static List<NvPreset> GetDefaultPresets()
|
||||
{
|
||||
var presets = new List<NvPreset>();
|
||||
@@ -121,30 +144,39 @@ namespace ColorControl
|
||||
public string GetTextForMenuItem()
|
||||
{
|
||||
var sb = new StringBuilder();
|
||||
if (displayName != null)
|
||||
if (!string.IsNullOrEmpty(name))
|
||||
{
|
||||
sb.AppendFormat("Display: {0} / ", displayName);
|
||||
}
|
||||
if (applyColorData)
|
||||
{
|
||||
var colorSettings = string.Format("Format: {0}, {1}, {2}", colorData.ColorDepth, colorData.ColorFormat, colorData.DynamicRange);
|
||||
sb.Append(colorSettings);
|
||||
sb.Append(name);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyRefreshRate)
|
||||
else
|
||||
{
|
||||
sb.AppendFormat("{0}Hz", refreshRate);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyDithering)
|
||||
{
|
||||
sb.AppendFormat("Dithering: {0}", ditheringEnabled ? "Yes" : "No");
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyHDR)
|
||||
{
|
||||
sb.AppendFormat("HDR: {0}", toggleHDR ? "Toggle" : HDREnabled ? "Enabled" : "Disabled");
|
||||
sb.Append(" / ");
|
||||
if (displayName != null)
|
||||
{
|
||||
sb.AppendFormat("Display: {0} / ", displayName);
|
||||
}
|
||||
if (applyColorData)
|
||||
{
|
||||
var colorSettings = string.Format("Format: {0}, {1}, {2}", colorData.ColorDepth, colorData.ColorFormat, colorData.DynamicRange);
|
||||
sb.Append(colorSettings);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyRefreshRate)
|
||||
{
|
||||
sb.AppendFormat("{0}Hz", refreshRate);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyDithering)
|
||||
{
|
||||
var dithering = GetDitheringDescription("No");
|
||||
sb.AppendFormat("Dithering: {0}", dithering);
|
||||
sb.Append(" / ");
|
||||
}
|
||||
if (applyHDR)
|
||||
{
|
||||
sb.AppendFormat("HDR: {0}", toggleHDR ? "Toggle" : HDREnabled ? "Enabled" : "Disabled");
|
||||
sb.Append(" / ");
|
||||
}
|
||||
}
|
||||
|
||||
return sb.ToString(0, Math.Max(0, sb.Length - 3));
|
||||
@@ -174,11 +206,16 @@ namespace ColorControl
|
||||
{
|
||||
dynamicRange = (ColorDataDynamicRange)Enum.ToObject(typeof(ColorDataDynamicRange), value);
|
||||
}
|
||||
if (dictionary.TryGetValue("SelectionPolicy", out value))
|
||||
if (dictionary.TryGetValue("SelectionPolicy", out _))
|
||||
{
|
||||
selectionPolicy = (ColorDataSelectionPolicy)Enum.ToObject(typeof(ColorDataSelectionPolicy), value);
|
||||
selectionPolicy =
|
||||
colorDepth == ColorDataDepth.Default &&
|
||||
format >= ColorDataFormat.Default &&
|
||||
colorimetry >= ColorDataColorimetry.Default &&
|
||||
dynamicRange == ColorDataDynamicRange.Auto ?
|
||||
ColorDataSelectionPolicy.BestQuality : selectionPolicy;
|
||||
}
|
||||
return new ColorData(format, dynamicRange: dynamicRange, colorimetry: colorimetry, colorDepth: colorDepth, colorSelectionPolicy: selectionPolicy);
|
||||
return new ColorData(format, dynamicRange: dynamicRange, colorimetry: colorimetry, colorDepth: colorDepth, colorSelectionPolicy: selectionPolicy, desktopColorDepth: ColorDataDesktopDepth.Default);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+416
-56
@@ -1,21 +1,61 @@
|
||||
using NvAPIWrapper;
|
||||
using Newtonsoft.Json;
|
||||
using NvAPIWrapper;
|
||||
using NvAPIWrapper.Display;
|
||||
using NvAPIWrapper.Native.Display;
|
||||
using NvAPIWrapper.Native.GPU.Structures;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class NvService : GraphicsService
|
||||
enum NvDitherState
|
||||
{
|
||||
[Description("Auto")]
|
||||
Auto = 0,
|
||||
[Description("Enabled")]
|
||||
Enabled = 1,
|
||||
[Description("Disabled")]
|
||||
Disabled = 2
|
||||
}
|
||||
|
||||
enum NvDitherBits
|
||||
{
|
||||
[Description("6-bit")]
|
||||
Bits6 = 0,
|
||||
[Description("8-bit")]
|
||||
Bits8 = 1,
|
||||
[Description("10-bit")]
|
||||
Bits10 = 2
|
||||
}
|
||||
|
||||
enum NvDitherMode
|
||||
{
|
||||
[Description("Spatial Dynamic")]
|
||||
SpatialDynamic = 0,
|
||||
[Description("Spatial Static")]
|
||||
SpatialStatic = 1,
|
||||
[Description("Spatial Dynamic 2x2")]
|
||||
SpatialDynamic2x2 = 2,
|
||||
[Description("Spatial Static 2x2")]
|
||||
SpatialStatic2x2 = 3,
|
||||
[Description("Temporal")]
|
||||
Temporal = 4
|
||||
}
|
||||
|
||||
class NvService : GraphicsService<NvPreset>
|
||||
{
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
[DllImport(@"nvapi64", EntryPoint = @"nvapi_QueryInterface", CallingConvention = CallingConvention.Cdecl,
|
||||
PreserveSig = true)]
|
||||
private static extern IntPtr NvAPI64_QueryInterface(uint interfaceId);
|
||||
|
||||
public delegate long NvAPI_Disp_SetDitherControl(
|
||||
public delegate int NvAPI_Disp_SetDitherControl(
|
||||
[In] PhysicalGPUHandle physicalGpu,
|
||||
[In] uint OutputId,
|
||||
[In] uint state,
|
||||
@@ -23,29 +63,60 @@ namespace ColorControl
|
||||
[In] uint mode
|
||||
);
|
||||
|
||||
public delegate long NvAPI_Disp_GetDitherControl(
|
||||
[In] PhysicalGPUHandle physicalGpu,
|
||||
[In] uint OutputId,
|
||||
[In][Out] IntPtr ditherControl);
|
||||
public delegate int NvAPI_Disp_GetDitherControl(
|
||||
[In] uint DisplayId,
|
||||
[MarshalAs(UnmanagedType.Struct)] ref NV_GPU_DITHER_CONTROL_V1 ditherControl);
|
||||
|
||||
[StructLayout(LayoutKind.Sequential, Pack = 8)]
|
||||
[StructLayout(LayoutKind.Sequential)]
|
||||
public struct NV_GPU_DITHER_CONTROL_V1
|
||||
{
|
||||
public int version;
|
||||
public uint state;
|
||||
public uint bits;
|
||||
public uint mode;
|
||||
public uint version;
|
||||
public int state;
|
||||
public int bits;
|
||||
public int mode;
|
||||
public uint bitsCaps;
|
||||
public uint modeCaps;
|
||||
};
|
||||
|
||||
private Display _currentDisplay;
|
||||
private bool _initialized = false;
|
||||
|
||||
public NvService()
|
||||
public NvService(string dataPath) : base(dataPath, "NvPresets.json")
|
||||
{
|
||||
AddJsonConverter(new ColorDataConverter());
|
||||
|
||||
LoadPresets();
|
||||
}
|
||||
|
||||
public static bool ExecutePresetAsync(string idOrName)
|
||||
{
|
||||
try
|
||||
{
|
||||
var nvService = new NvService(Program.DataDir);
|
||||
|
||||
var result = nvService.ApplyPreset(idOrName);
|
||||
|
||||
if (!result)
|
||||
{
|
||||
Console.WriteLine("Preset not found or error while executing.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Console.WriteLine("Error executing preset: " + ex.ToLogString());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public Display GetCurrentDisplay()
|
||||
{
|
||||
if (!HasDisplaysAttached())
|
||||
{
|
||||
_currentDisplay = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
if (_currentDisplay == null)
|
||||
{
|
||||
_currentDisplay = Display.GetDisplays()[0];
|
||||
@@ -54,6 +125,54 @@ namespace ColorControl
|
||||
return _currentDisplay;
|
||||
}
|
||||
|
||||
public override bool HasDisplaysAttached(bool reinitialize = false)
|
||||
{
|
||||
if (reinitialize)
|
||||
{
|
||||
try
|
||||
{
|
||||
Initialize();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"Could not reinitialize NVIDIA API: {ex.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
return DisplayDevice.GetGDIPrimaryDisplayDevice() != null;
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return reinitialize ? false : HasDisplaysAttached(true);
|
||||
}
|
||||
}
|
||||
|
||||
public void GlobalSave()
|
||||
{
|
||||
SavePresets();
|
||||
}
|
||||
|
||||
protected override List<NvPreset> GetDefaultPresets()
|
||||
{
|
||||
return NvPreset.GetDefaultPresets();
|
||||
}
|
||||
|
||||
private void SavePresets()
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = JsonConvert.SerializeObject(_presets);
|
||||
File.WriteAllText(_presetsFilename, json);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error(e.ToLogString());
|
||||
}
|
||||
}
|
||||
|
||||
private void SetCurrentDisplay(NvPreset preset)
|
||||
{
|
||||
if (preset.primaryDisplay)
|
||||
@@ -68,106 +187,261 @@ namespace ColorControl
|
||||
}
|
||||
|
||||
|
||||
public bool ApplyPreset(NvPreset preset, Config config)
|
||||
public bool ApplyPreset(string idOrName)
|
||||
{
|
||||
var preset = GetPresetByIdOrName(idOrName);
|
||||
if (preset != null)
|
||||
{
|
||||
return ApplyPreset(preset, Program.AppContext);
|
||||
}
|
||||
else
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public bool ApplyPreset(NvPreset preset, AppContext appContext)
|
||||
{
|
||||
var result = true;
|
||||
|
||||
if (!HasDisplaysAttached())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
SetCurrentDisplay(preset);
|
||||
|
||||
if (preset.applyHDR)
|
||||
{
|
||||
if (preset.toggleHDR || preset.HDREnabled != IsHDREnabled())
|
||||
{
|
||||
ToggleHDR(config.DisplaySettingsDelay);
|
||||
}
|
||||
}
|
||||
var hdrEnabled = IsHDREnabled();
|
||||
|
||||
if (preset.applyRefreshRate)
|
||||
{
|
||||
SetRefreshRate(preset.refreshRate);
|
||||
}
|
||||
var newHdrEnabled = preset.applyHDR && (preset.HDREnabled || (preset.toggleHDR && !hdrEnabled));
|
||||
var applyHdr = preset.applyHDR && (preset.toggleHDR || preset.HDREnabled != hdrEnabled);
|
||||
|
||||
if (preset.applyColorData)
|
||||
if (preset.applyColorData && (ColorDataDiffers(preset.colorData) || (!newHdrEnabled && preset.applyColorData && preset.colorData.Colorimetry != ColorDataColorimetry.Auto)))
|
||||
{
|
||||
var display = GetCurrentDisplay();
|
||||
//var data = new ColorData(ColorDataFormat.YUV444, ColorDataColorimetry.Auto, ColorDataDynamicRange.Auto, ColorDataDepth.BPC10, preset.colorData.SelectionPolicy, ColorDataDesktopDepth.Default);
|
||||
if (display == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
if (hdrEnabled)
|
||||
{
|
||||
SetHDRState(display, false);
|
||||
|
||||
applyHdr = false;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
display.DisplayDevice.SetColorData(preset.colorData);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"SetColorData threw an exception: {ex.Message}");
|
||||
result = false;
|
||||
}
|
||||
|
||||
//var master = display.DisplayDevice.HDRColorData.MasteringDisplayData;
|
||||
//var newMaster = new MasteringDisplayColorData(master.FirstColorCoordinate, master.SecondColorCoordinate, master.ThirdColorCoordinate, new ColorDataColorCoordinate(0.25f, 0.25f), 50, 0, 50, 50);
|
||||
//var hdr = new HDRColorData(ColorDataHDRMode.UHDA, newMaster, ColorDataFormat.YUV444, ColorDataDynamicRange.Auto, ColorDataDepth.BPC8);
|
||||
//display.DisplayDevice.SetHDRColorData(hdr);
|
||||
if (hdrEnabled && newHdrEnabled)
|
||||
{
|
||||
SetHDRState(display, true, useSwitch: appContext.StartUpParams.NoGui);
|
||||
|
||||
applyHdr = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (applyHdr)
|
||||
{
|
||||
var display = GetCurrentDisplay();
|
||||
if (display == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var colorData = preset.applyColorData ? preset.colorData : display.DisplayDevice.CurrentColorData;
|
||||
|
||||
SetHDRState(display, newHdrEnabled, colorData, appContext.StartUpParams.NoGui);
|
||||
}
|
||||
|
||||
if (preset.applyRefreshRate)
|
||||
{
|
||||
if (!SetRefreshRate(preset.refreshRate))
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (preset.applyDithering)
|
||||
{
|
||||
SetDithering(preset.ditheringEnabled);
|
||||
if (!SetDithering(preset.ditheringEnabled ? NvDitherState.Enabled : NvDitherState.Disabled, preset: preset))
|
||||
{
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
_lastAppliedPreset = preset;
|
||||
|
||||
PresetApplied();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void SetDithering(bool enabled)
|
||||
private ColorData GetCurrentColorData(Display display)
|
||||
{
|
||||
try
|
||||
{
|
||||
return display.DisplayDevice.CurrentColorData;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error while reading current color data: " + e.Message);
|
||||
return new ColorData();
|
||||
}
|
||||
}
|
||||
|
||||
private bool ColorDataDiffers(ColorData colorData)
|
||||
{
|
||||
var display = GetCurrentDisplay();
|
||||
|
||||
var currentColorData = GetCurrentColorData(display);
|
||||
|
||||
var settingRange = colorData.DynamicRange == ColorDataDynamicRange.Auto ? colorData.ColorFormat == ColorDataFormat.RGB ? ColorDataDynamicRange.VESA : ColorDataDynamicRange.CEA : colorData.DynamicRange;
|
||||
|
||||
var settingSpace = colorData.Colorimetry;
|
||||
|
||||
return colorData.ColorFormat != currentColorData.ColorFormat || colorData.ColorDepth != currentColorData.ColorDepth || settingRange != currentColorData.DynamicRange || settingSpace != currentColorData.Colorimetry;
|
||||
}
|
||||
|
||||
private void SetHDRState(Display display, bool enabled, ColorData colorData = null, bool useSwitch = false)
|
||||
{
|
||||
if (useSwitch)
|
||||
{
|
||||
if (enabled != IsHDREnabled())
|
||||
{
|
||||
CCD.SetHDRState(enabled, display.Name);
|
||||
//ToggleHDR();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
CCD.SetHDRState(enabled, display.Name);
|
||||
|
||||
//var newMaster = new MasteringDisplayColorData();
|
||||
//var hdr = new HDRColorData(enabled ? ColorDataHDRMode.UHDA : ColorDataHDRMode.Off, newMaster, colorData?.ColorFormat, colorData?.DynamicRange, colorData?.ColorDepth);
|
||||
|
||||
//display.DisplayDevice.SetHDRColorData(hdr);
|
||||
|
||||
// HDR will not always be disabled this way, then we can only disable it through the display settings
|
||||
//if (!enabled && IsHDREnabled())
|
||||
//{
|
||||
// CCD.SetHDRState(enabled);
|
||||
// //ToggleHDR();
|
||||
//}
|
||||
//else if (enabled)
|
||||
//{
|
||||
// // Currectly there seems to be a bug that after enabling HDR via NVAPI, some settings are only applied upon opening the Display Settings...
|
||||
// ////OpenDisplaySettings();
|
||||
//}
|
||||
}
|
||||
|
||||
public bool SetDithering(NvDitherState state, uint bits = 1, uint mode = 4, NvPreset preset = null)
|
||||
{
|
||||
var result = true;
|
||||
|
||||
var ptr = NvAPI64_QueryInterface(0xDF0DFCDD);
|
||||
if (ptr != IntPtr.Zero)
|
||||
{
|
||||
var delegateValue = Marshal.GetDelegateForFunctionPointer(ptr, typeof(NvAPI_Disp_SetDitherControl)) as NvAPI_Disp_SetDitherControl;
|
||||
|
||||
var displayDevice = GetCurrentDisplay().DisplayDevice;
|
||||
var display = GetCurrentDisplay();
|
||||
if (display == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var displayDevice = display.DisplayDevice;
|
||||
|
||||
var gpuHandle = displayDevice.PhysicalGPU.Handle;
|
||||
var displayId = displayDevice.DisplayId;
|
||||
|
||||
var result = delegateValue(gpuHandle, displayId, (uint)(enabled ? 1 : 2), 1, 4);
|
||||
if (result != 0)
|
||||
|
||||
if (state == NvDitherState.Auto)
|
||||
{
|
||||
Logger.Error($"Could not set dithering because NvAPI_Disp_SetDitherControl returned a non-zero return code: {result}");
|
||||
// These seem to be ignored in Auto-state
|
||||
bits = 0;
|
||||
mode = 0;
|
||||
}
|
||||
else if (preset != null)
|
||||
{
|
||||
bits = preset.ditheringBits;
|
||||
mode = preset.ditheringMode;
|
||||
}
|
||||
|
||||
var resultValue = delegateValue(gpuHandle, displayId, (uint)state, bits, mode);
|
||||
if (resultValue != 0)
|
||||
{
|
||||
Logger.Error($"Could not set dithering because NvAPI_Disp_SetDitherControl returned a non-zero return code: {resultValue}");
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Logger.Error($"Could not set dithering because the function NvAPI_Disp_SetDitherControl could not be found");
|
||||
result = false;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool GetDithering()
|
||||
public NV_GPU_DITHER_CONTROL_V1 GetDithering()
|
||||
{
|
||||
var dither = new NV_GPU_DITHER_CONTROL_V1 { version = 0x10018 };
|
||||
|
||||
var ptr = NvAPI64_QueryInterface(0x932AC8FB);
|
||||
if (ptr != IntPtr.Zero)
|
||||
{
|
||||
var delegateValue = Marshal.GetDelegateForFunctionPointer(ptr, typeof(NvAPI_Disp_GetDitherControl)) as NvAPI_Disp_GetDitherControl;
|
||||
|
||||
var displayDevice = GetCurrentDisplay().DisplayDevice;
|
||||
var display = GetCurrentDisplay();
|
||||
if (display == null)
|
||||
{
|
||||
dither.state = -1;
|
||||
return dither;
|
||||
}
|
||||
|
||||
var gpuHandle = displayDevice.PhysicalGPU.Handle;
|
||||
var displayDevice = display.DisplayDevice;
|
||||
var displayId = displayDevice.DisplayId;
|
||||
|
||||
NV_GPU_DITHER_CONTROL_V1 info = new NV_GPU_DITHER_CONTROL_V1();
|
||||
info.version = 1;
|
||||
IntPtr bla = Marshal.AllocHGlobal(Marshal.SizeOf(info.GetType()));
|
||||
Marshal.StructureToPtr(info, bla, false);
|
||||
|
||||
// Does not work yet...What is the exact interface of NvAPI_Disp_GetDitherControl?
|
||||
|
||||
var result = delegateValue(gpuHandle, displayId, bla);
|
||||
var result = delegateValue(displayId, ref dither);
|
||||
if (result != 0)
|
||||
{
|
||||
Logger.Error($"Could not get dithering because NvAPI_Disp_GetDitherControl returned a non-zero return code: {result}");
|
||||
dither.state = -1;
|
||||
}
|
||||
|
||||
return info.state == 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
dither.state = -2;
|
||||
}
|
||||
|
||||
return false;
|
||||
return dither;
|
||||
}
|
||||
|
||||
public bool SetRefreshRate(uint refreshRate)
|
||||
{
|
||||
var display = GetCurrentDisplay();
|
||||
var portrait = new[] { Rotate.Degree90, Rotate.Degree270 }.Contains(display.DisplayDevice.ScanOutInformation.SourceToTargetRotation);
|
||||
if (display == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var timing = display.DisplayDevice.CurrentTiming;
|
||||
|
||||
if (timing.Extra.RefreshRate == refreshRate)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
var portrait = new[] { Rotate.Degree90, Rotate.Degree270 }.Contains(display.DisplayDevice.ScanOutInformation.SourceToTargetRotation);
|
||||
|
||||
return SetRefreshRateInternal(display.Name, refreshRate, portrait, timing.HorizontalVisible, timing.VerticalVisible);
|
||||
}
|
||||
|
||||
@@ -179,6 +453,11 @@ namespace ColorControl
|
||||
}
|
||||
|
||||
var display = GetCurrentDisplay();
|
||||
if (display == null)
|
||||
{
|
||||
return new List<uint>();
|
||||
}
|
||||
|
||||
var portrait = new[] { Rotate.Degree90, Rotate.Degree270 }.Contains(display.DisplayDevice.ScanOutInformation.SourceToTargetRotation);
|
||||
var timing = display.DisplayDevice.CurrentTiming;
|
||||
|
||||
@@ -187,7 +466,13 @@ namespace ColorControl
|
||||
|
||||
public bool IsHDREnabled()
|
||||
{
|
||||
var displayDevice = GetCurrentDisplay().DisplayDevice;
|
||||
var display = GetCurrentDisplay();
|
||||
if (display == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var displayDevice = display.DisplayDevice;
|
||||
var hdr = displayDevice.HDRColorData;
|
||||
return hdr?.HDRMode == ColorDataHDRMode.UHDA;
|
||||
}
|
||||
@@ -197,6 +482,81 @@ namespace ColorControl
|
||||
return Display.GetDisplays();
|
||||
}
|
||||
|
||||
public List<NvDisplayInfo> GetDisplayInfos()
|
||||
{
|
||||
Display[] displays;
|
||||
try
|
||||
{
|
||||
displays = GetDisplays();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("Error while getting displays: " + e.ToLogString());
|
||||
return null;
|
||||
}
|
||||
|
||||
var list = new List<NvDisplayInfo>();
|
||||
|
||||
foreach (var display in displays)
|
||||
{
|
||||
var values = new List<string>();
|
||||
|
||||
values.Add("Current settings");
|
||||
|
||||
var name = display.Name;
|
||||
|
||||
var screen = Screen.AllScreens.FirstOrDefault(x => x.DeviceName.Equals(name));
|
||||
if (screen != null)
|
||||
{
|
||||
name += " (" + screen.DeviceFriendlyName() + ")";
|
||||
}
|
||||
|
||||
values.Add(name);
|
||||
|
||||
var colorData = GetCurrentColorData(display);
|
||||
|
||||
var colorSettings = string.Format("{0}, {1}, {2}, {3}", colorData.ColorDepth, colorData.ColorFormat, colorData.DynamicRange, colorData.Colorimetry);
|
||||
|
||||
values.Add(colorSettings);
|
||||
|
||||
var refreshRate = display.DisplayDevice.CurrentTiming.Extra.RefreshRate;
|
||||
|
||||
values.Add($"{refreshRate}Hz");
|
||||
|
||||
var ditherInfo = GetDithering();
|
||||
|
||||
string dithering;
|
||||
if (ditherInfo.state == -1)
|
||||
{
|
||||
dithering = "Error";
|
||||
}
|
||||
else
|
||||
{
|
||||
var state = (NvDitherState)ditherInfo.state;
|
||||
dithering = state switch { NvDitherState.Disabled => "Disabled", NvDitherState.Auto => "Auto: ", _ => string.Empty };
|
||||
if (state is NvDitherState.Enabled or NvDitherState.Auto)
|
||||
{
|
||||
var ditherBitsDescription = ((NvDitherBits)ditherInfo.bits).GetDescription();
|
||||
var ditherModeDescription = ((NvDitherMode)ditherInfo.mode).GetDescription();
|
||||
dithering = string.Format("{0}{1} {2}", dithering, ditherBitsDescription, ditherModeDescription);
|
||||
}
|
||||
}
|
||||
|
||||
values.Add(dithering);
|
||||
|
||||
var hdrEnabled = IsHDREnabled();
|
||||
values.Add(hdrEnabled ? "Yes" : "No");
|
||||
|
||||
var infoLine = string.Format("{0}: {1}, {2}Hz, HDR: {3}", name, colorSettings, refreshRate, hdrEnabled ? "Yes" : "No");
|
||||
|
||||
var displayInfo = new NvDisplayInfo(display, values, infoLine);
|
||||
|
||||
list.Add(displayInfo);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
protected override void Initialize()
|
||||
{
|
||||
NVIDIA.Initialize();
|
||||
|
||||
+17
-5
@@ -1,11 +1,14 @@
|
||||
using Windows.Devices.Enumeration;
|
||||
using Newtonsoft.Json;
|
||||
using Windows.Devices.Enumeration;
|
||||
using Windows.Devices.Enumeration.Pnp;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class PnpDev
|
||||
{
|
||||
[JsonIgnore]
|
||||
public DeviceInformation DevInfo { get; private set; }
|
||||
[JsonIgnore]
|
||||
public PnpObject PnpObject { get; private set; }
|
||||
|
||||
public string Name { get; private set; }
|
||||
@@ -13,18 +16,27 @@ namespace ColorControl
|
||||
|
||||
public string MacAddress { get; private set; }
|
||||
|
||||
public PnpDev(DeviceInformation devInfo, PnpObject pnpObject, string name, string ipAddress, string macAddress)
|
||||
[JsonConstructor]
|
||||
public PnpDev(string name, string ipAddress, string macAddress)
|
||||
{
|
||||
DevInfo = devInfo;
|
||||
PnpObject = pnpObject;
|
||||
Name = name;
|
||||
IpAddress = ipAddress;
|
||||
MacAddress = macAddress;
|
||||
}
|
||||
public PnpDev(DeviceInformation devInfo, PnpObject pnpObject, string name, string ipAddress, string macAddress) : this(name, ipAddress, macAddress)
|
||||
{
|
||||
DevInfo = devInfo;
|
||||
PnpObject = pnpObject;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Name + " (" + IpAddress + ")";
|
||||
return (IsCustom() ? "Custom: " : "Auto detect: ") + $"{Name}" + (!string.IsNullOrEmpty(IpAddress) ? $"({IpAddress})" : string.Empty);
|
||||
}
|
||||
|
||||
public bool IsCustom()
|
||||
{
|
||||
return DevInfo == null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,127 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
enum PresetTriggerType
|
||||
{
|
||||
[Description("None")]
|
||||
None = 0,
|
||||
[Description("Startup")]
|
||||
Startup = 1,
|
||||
[Description("Resume")]
|
||||
Resume = 2,
|
||||
[Description("Shutdown")]
|
||||
Shutdown = 3,
|
||||
[Description("Standby")]
|
||||
Standby = 4,
|
||||
[Description("Reserved5")]
|
||||
Reserved5 = 5,
|
||||
[Description("Process switch")]
|
||||
ProcessSwitch = 6,
|
||||
[Description("Screensaver start")]
|
||||
ScreensaverStart = 7,
|
||||
[Description("Screensaver stop")]
|
||||
ScreensaverStop = 8,
|
||||
}
|
||||
|
||||
[Flags]
|
||||
enum PresetConditionType
|
||||
{
|
||||
[Description("None")]
|
||||
None = 0,
|
||||
[Description("SDR")]
|
||||
SDR = 1,
|
||||
[Description("HDR")]
|
||||
HDR = 2,
|
||||
[Description("Full Screen")]
|
||||
FullScreen = 4,
|
||||
[Description("Notifications Disabled")]
|
||||
NotificationsDisabled = 8,
|
||||
}
|
||||
|
||||
class PresetTrigger
|
||||
{
|
||||
public PresetTriggerType Trigger { get; set; }
|
||||
public List<string> IncludedProcesses { get; set; }
|
||||
public List<string> ExcludedProcesses { get; set; }
|
||||
public PresetConditionType Conditions { get; set; }
|
||||
|
||||
public PresetTrigger()
|
||||
{
|
||||
IncludedProcesses = new List<string>();
|
||||
ExcludedProcesses = new List<string>();
|
||||
}
|
||||
|
||||
public bool TriggerActive(PresetTriggerContext context)
|
||||
{
|
||||
var active = Conditions == PresetConditionType.None || (Conditions.HasFlag(PresetConditionType.SDR) && !context.IsHDRActive) || (Conditions.HasFlag(PresetConditionType.HDR) && context.IsHDRActive);
|
||||
var allProcesses = IncludedProcesses.Contains("*");
|
||||
|
||||
if (Trigger == PresetTriggerType.ProcessSwitch)
|
||||
{
|
||||
active = active && (allProcesses || (context.ChangedProcesses?.Any() ?? false));
|
||||
|
||||
if (active)
|
||||
{
|
||||
var included = allProcesses || context.ChangedProcesses.Any(cp => IncludedProcesses.Any(ip => cp.ProcessName.Equals(ip, StringComparison.OrdinalIgnoreCase)));
|
||||
var excluded = context.ChangedProcesses.Any(cp => ExcludedProcesses.Any(ep => cp.ProcessName.Equals(ep, StringComparison.OrdinalIgnoreCase)));
|
||||
|
||||
var screenSizeCheck = (!Conditions.HasFlag(PresetConditionType.FullScreen) && !context.ForegroundProcessIsFullScreen) ||
|
||||
(context.ForegroundProcess != null && context.ForegroundProcessIsFullScreen &&
|
||||
(allProcesses || IncludedProcesses.Any(ip => context.ForegroundProcess.ProcessName.Equals(ip, StringComparison.OrdinalIgnoreCase))));
|
||||
|
||||
var notificationsDisabledCheck = !Conditions.HasFlag(PresetConditionType.NotificationsDisabled) || context.IsNotificationDisabled;
|
||||
|
||||
active = included && !excluded && screenSizeCheck && notificationsDisabledCheck;
|
||||
}
|
||||
}
|
||||
|
||||
return active;
|
||||
}
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
if (Trigger == PresetTriggerType.None)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
return $"On {Trigger.GetDescription()} of {DisplayProcesses(IncludedProcesses)}{(ExcludedProcesses.Any() ? ", excluding " + DisplayProcesses(ExcludedProcesses) : string.Empty)}{(Conditions > 0 ? ", only in " + string.Join(", ", Utils.GetDescriptions<PresetConditionType>((int)Conditions)) : string.Empty)}";
|
||||
}
|
||||
|
||||
public static string DisplayProcesses(IEnumerable<string> processes)
|
||||
{
|
||||
return processes.Contains("*") ? "all processes" : string.Join(", ", processes);
|
||||
}
|
||||
}
|
||||
|
||||
class PresetTriggerContext
|
||||
{
|
||||
public bool IsHDRActive { get; set; }
|
||||
public Process ForegroundProcess { get; set; }
|
||||
public bool ForegroundProcessIsFullScreen { get; set; }
|
||||
public List<Process> ChangedProcesses { get; set; }
|
||||
public bool IsNotificationDisabled { get; set; }
|
||||
}
|
||||
|
||||
internal abstract class PresetBase
|
||||
{
|
||||
public string name { get; set; }
|
||||
public string shortcut { get; set; }
|
||||
public List<PresetTrigger> Triggers { get; set; }
|
||||
|
||||
private int _id;
|
||||
|
||||
protected PresetBase()
|
||||
{
|
||||
Triggers = new List<PresetTrigger>();
|
||||
}
|
||||
|
||||
public int id
|
||||
{
|
||||
get
|
||||
@@ -45,5 +158,40 @@ namespace ColorControl
|
||||
return id;
|
||||
}
|
||||
|
||||
public abstract List<string> GetDisplayValues(Config config = null);
|
||||
|
||||
public void UpdateTrigger(PresetTriggerType triggerType, PresetConditionType conditions, string includedProcesses, string excludedProcesses)
|
||||
{
|
||||
if (!Triggers.Any())
|
||||
{
|
||||
Triggers.Add(new PresetTrigger());
|
||||
}
|
||||
|
||||
var trigger = Triggers.First();
|
||||
|
||||
trigger.Trigger = triggerType;
|
||||
trigger.Conditions = conditions;
|
||||
|
||||
if (trigger.IncludedProcesses == null)
|
||||
{
|
||||
trigger.IncludedProcesses = new List<string>();
|
||||
}
|
||||
if (trigger.ExcludedProcesses == null)
|
||||
{
|
||||
trigger.ExcludedProcesses = new List<string>();
|
||||
}
|
||||
Utils.ParseWords(trigger.IncludedProcesses, includedProcesses);
|
||||
Utils.ParseWords(trigger.ExcludedProcesses, excludedProcesses);
|
||||
}
|
||||
|
||||
public PresetTrigger AddTrigger()
|
||||
{
|
||||
if (!Triggers.Any())
|
||||
{
|
||||
Triggers.Add(new PresetTrigger());
|
||||
}
|
||||
|
||||
return Triggers.First();
|
||||
}
|
||||
}
|
||||
}
|
||||
+175
-7
@@ -1,4 +1,9 @@
|
||||
using System;
|
||||
using Newtonsoft.Json;
|
||||
using NLog;
|
||||
using NWin32;
|
||||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.IO;
|
||||
using System.Threading;
|
||||
using System.Windows.Forms;
|
||||
|
||||
@@ -6,6 +11,13 @@ namespace ColorControl
|
||||
{
|
||||
static class Program
|
||||
{
|
||||
public const string TS_TASKNAME = "ColorControl";
|
||||
public static string DataDir { get; private set; }
|
||||
public static string ConfigFilename { get; private set; }
|
||||
public static Config Config { get; private set; }
|
||||
public static AppContext AppContext { get; private set; }
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// The main entry point for the application.
|
||||
/// </summary>
|
||||
@@ -18,21 +30,48 @@ namespace ColorControl
|
||||
// Handler for exceptions in threads behind forms.
|
||||
Application.ThreadException += GlobalThreadExceptionHandler;
|
||||
|
||||
DataDir = Utils.GetDataPath();
|
||||
InitLogger();
|
||||
|
||||
LoadConfig();
|
||||
|
||||
if (Config.UseGdiScaling)
|
||||
{
|
||||
Application.SetHighDpiMode(HighDpiMode.DpiUnawareGdiScaled);
|
||||
}
|
||||
|
||||
var startUpParams = StartUpParams.Parse(args);
|
||||
|
||||
if (startUpParams.ActivateChromeFontFix || startUpParams.DeactivateChromeFontFix)
|
||||
AppContext = new AppContext(Config, startUpParams);
|
||||
|
||||
var existingProcess = Utils.GetProcessByName("ColorControl");
|
||||
|
||||
try
|
||||
{
|
||||
Utils.InstallChromeFix(startUpParams.ActivateChromeFontFix);
|
||||
return;
|
||||
if (HandleStartupParams(startUpParams, existingProcess))
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Utils.CloseConsole();
|
||||
}
|
||||
|
||||
string mutexId = $"Global\\{typeof(MainForm).GUID}";
|
||||
bool mutexCreated;
|
||||
var mutex = new Mutex(true, mutexId, out mutexCreated);
|
||||
var mutex = new Mutex(true, mutexId, out var mutexCreated);
|
||||
try
|
||||
{
|
||||
if (!mutexCreated)
|
||||
{
|
||||
if (existingProcess != null && existingProcess.Threads.Count > 0)
|
||||
{
|
||||
var thread = existingProcess.Threads[0];
|
||||
NativeMethods.EnumThreadWindows((uint)thread.Id, EnumThreadWindows, IntPtr.Zero);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
MessageBox.Show("Only one instance of this program can be active.", "ColorControl");
|
||||
}
|
||||
else
|
||||
@@ -41,7 +80,7 @@ namespace ColorControl
|
||||
{
|
||||
Application.EnableVisualStyles();
|
||||
Application.SetCompatibleTextRenderingDefault(false);
|
||||
Application.Run(new MainForm(startUpParams));
|
||||
Application.Run(new MainForm(AppContext));
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
@@ -58,6 +97,135 @@ namespace ColorControl
|
||||
}
|
||||
}
|
||||
|
||||
private static void InitLogger()
|
||||
{
|
||||
var config = new NLog.Config.LoggingConfiguration();
|
||||
|
||||
// Targets where to log to: File and Console
|
||||
var logfile = new NLog.Targets.FileTarget("logfile") { FileName = Path.Combine(DataDir, "LogFile.txt") };
|
||||
//var logconsole = new NLog.Targets.ConsoleTarget("logconsole");
|
||||
|
||||
// Rules for mapping loggers to targets
|
||||
//config.AddRule(LogLevel.Info, LogLevel.Fatal, logconsole);
|
||||
config.AddRule(LogLevel.Trace, LogLevel.Fatal, logfile);
|
||||
|
||||
// Apply config
|
||||
LogManager.Configuration = config;
|
||||
}
|
||||
|
||||
private static void LoadConfig()
|
||||
{
|
||||
ConfigFilename = Path.Combine(DataDir, "Settings.json");
|
||||
|
||||
if (File.Exists(ConfigFilename))
|
||||
{
|
||||
var data = File.ReadAllText(ConfigFilename);
|
||||
Config = JsonConvert.DeserializeObject<Config>(data);
|
||||
}
|
||||
else
|
||||
{
|
||||
Config = new Config();
|
||||
}
|
||||
}
|
||||
|
||||
private static bool HandleStartupParams(StartUpParams startUpParams, Process existingProcess)
|
||||
{
|
||||
if (startUpParams.ActivateChromeFontFix || startUpParams.DeactivateChromeFontFix)
|
||||
{
|
||||
Utils.InstallChromeFix(startUpParams.ActivateChromeFontFix);
|
||||
return true;
|
||||
}
|
||||
if (startUpParams.EnableAutoStart || startUpParams.DisableAutoStart)
|
||||
{
|
||||
Utils.RegisterTask(TS_TASKNAME, startUpParams.EnableAutoStart);
|
||||
return true;
|
||||
}
|
||||
|
||||
var useConsole = startUpParams.NoGui || existingProcess != null;
|
||||
|
||||
if (!useConsole)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
startUpParams.NoGui = true;
|
||||
|
||||
var result = false;
|
||||
|
||||
if (startUpParams.ExecuteHelp)
|
||||
{
|
||||
Utils.OpenConsole();
|
||||
|
||||
Console.WriteLine("\nColorControl CLI");
|
||||
Console.WriteLine("Syntax : ColorControl command options");
|
||||
Console.WriteLine("Commands:");
|
||||
Console.WriteLine("--nvpreset <preset name or id>: execute NVIDIA-preset");
|
||||
Console.WriteLine("--amdpreset <preset name or id>: execute AMD-preset");
|
||||
Console.WriteLine("--lgpreset <preset name> : execute LG-preset");
|
||||
Console.WriteLine("--help : displays this help info");
|
||||
Console.WriteLine("Options:");
|
||||
Console.WriteLine("--nogui: starts command from the command line and will not open GUI (is forced when GUI is already running)");
|
||||
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (startUpParams.ExecuteLgPreset)
|
||||
{
|
||||
Utils.OpenConsole();
|
||||
|
||||
Console.WriteLine($"Executing LG-preset '{startUpParams.LgPresetName}'...");
|
||||
var task = LgService.ExecutePresetAsync(startUpParams.LgPresetName);
|
||||
|
||||
var taskResult = Utils.WaitForTask(task);
|
||||
|
||||
if (taskResult)
|
||||
{
|
||||
Console.WriteLine("Done.");
|
||||
}
|
||||
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (startUpParams.ExecuteNvidiaPreset)
|
||||
{
|
||||
Utils.OpenConsole();
|
||||
|
||||
Console.WriteLine($"Executing NVIDIA-preset '{startUpParams.NvidiaPresetIdOrName}'...");
|
||||
var taskResult = NvService.ExecutePresetAsync(startUpParams.NvidiaPresetIdOrName);
|
||||
|
||||
if (taskResult)
|
||||
{
|
||||
Console.WriteLine("Done.");
|
||||
}
|
||||
|
||||
result = true;
|
||||
}
|
||||
|
||||
if (startUpParams.ExecuteAmdPreset)
|
||||
{
|
||||
Utils.OpenConsole();
|
||||
|
||||
Console.WriteLine($"Executing AMD-preset '{startUpParams.AmdPresetIdOrName}'...");
|
||||
var taskResult = AmdService.ExecutePresetAsync(startUpParams.AmdPresetIdOrName);
|
||||
|
||||
if (taskResult)
|
||||
{
|
||||
Console.WriteLine("Done.");
|
||||
}
|
||||
|
||||
result = true;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int EnumThreadWindows(IntPtr handle, IntPtr param)
|
||||
{
|
||||
NativeMethods.SendMessageW(handle, Utils.WM_BRINGTOFRONT, UIntPtr.Zero, IntPtr.Zero);
|
||||
|
||||
return 1;
|
||||
}
|
||||
|
||||
private static void GlobalUnhandledExceptionHandler(object sender, UnhandledExceptionEventArgs e)
|
||||
{
|
||||
var ex = (Exception)e.ExceptionObject;
|
||||
|
||||
@@ -1,36 +0,0 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("ColorControl")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("Maassoft")]
|
||||
[assembly: AssemblyProduct("ColorControl")]
|
||||
[assembly: AssemblyCopyright("Copyright © Maassoft 2020")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("a6005d08-70f0-44cb-a384-9219eba84f21")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.3.6.0")]
|
||||
[assembly: AssemblyFileVersion("1.3.6.0")]
|
||||
+72
-26
@@ -8,10 +8,10 @@
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace ColorControl.Properties
|
||||
{
|
||||
|
||||
|
||||
namespace ColorControl.Properties {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// </summary>
|
||||
@@ -19,53 +19,99 @@ namespace ColorControl.Properties
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources
|
||||
{
|
||||
|
||||
internal class Resources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources()
|
||||
{
|
||||
internal Resources() {
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager
|
||||
{
|
||||
get
|
||||
{
|
||||
if ((resourceMan == null))
|
||||
{
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ColorControl.Properties.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture
|
||||
{
|
||||
get
|
||||
{
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set
|
||||
{
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized resource of type System.Drawing.Bitmap.
|
||||
/// </summary>
|
||||
internal static System.Drawing.Bitmap LG_remote {
|
||||
get {
|
||||
object obj = ResourceManager.GetObject("LG_remote", resourceCulture);
|
||||
return ((System.Drawing.Bitmap)(obj));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to Power;120;136
|
||||
///1;106;228
|
||||
///2;196;228
|
||||
///3;286;228
|
||||
///4;106;296
|
||||
///5;196;296
|
||||
///6;286;296
|
||||
///7;106;362
|
||||
///8;196;362
|
||||
///9;286;362
|
||||
///List;106;425
|
||||
///0;196;425
|
||||
///SAP;286;425
|
||||
///Vol +;98;513
|
||||
///Mute;198;513
|
||||
///Channel +;298;513
|
||||
///Vol -;98;622
|
||||
///Channel -;298;622
|
||||
///Home;78;695
|
||||
///Settings;318;695
|
||||
///Up;200;748
|
||||
///Left;98;852
|
||||
///Enter;200;852
|
||||
///Right;304;852
|
||||
///Down;200;952
|
||||
///Back;80;1000
|
||||
///TV Guide;320;1000
|
||||
///Netflix;92;1076
|
||||
///Inputs;200;1066
|
||||
///Amazon Prime;312;1076
|
||||
///Red;90;1150
|
||||
///Green;164;1150
|
||||
///Yellow;240;1150
|
||||
///Blue;316;1150
|
||||
///Rakuten TV;116;1218
|
||||
///Play;202 [rest of string was truncated]";.
|
||||
/// </summary>
|
||||
internal static string RC_coords {
|
||||
get {
|
||||
return ResourceManager.GetString("RC_coords", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
@@ -60,6 +60,7 @@
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
@@ -68,9 +69,10 @@
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
@@ -85,9 +87,10 @@
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" 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="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
@@ -109,9 +112,16 @@
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
|
||||
<data name="LG_remote" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\LG_remote.jpg;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a</value>
|
||||
</data>
|
||||
<data name="RC_coords" type="System.Resources.ResXFileRef, System.Windows.Forms">
|
||||
<value>..\Resources\RC_coords.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;Windows-1252</value>
|
||||
</data>
|
||||
</root>
|
||||
+9
-13
@@ -8,21 +8,17 @@
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace ColorControl.Properties
|
||||
{
|
||||
|
||||
|
||||
namespace ColorControl.Properties {
|
||||
|
||||
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
|
||||
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
|
||||
{
|
||||
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.0")]
|
||||
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
|
||||
|
||||
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
|
||||
|
||||
public static Settings Default
|
||||
{
|
||||
get
|
||||
{
|
||||
|
||||
public static Settings Default {
|
||||
get {
|
||||
return defaultInstance;
|
||||
}
|
||||
}
|
||||
|
||||
+197
@@ -0,0 +1,197 @@
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
partial class RemoteControlForm
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Windows Form Designer generated code
|
||||
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RemoteControlForm));
|
||||
this.flowPanel = new System.Windows.Forms.FlowLayoutPanel();
|
||||
this.btnClose = new System.Windows.Forms.Button();
|
||||
this.lblUC = new System.Windows.Forms.Label();
|
||||
this.chkDirectMode = new System.Windows.Forms.CheckBox();
|
||||
this.pnlMouse = new System.Windows.Forms.Panel();
|
||||
this.lblPos = new System.Windows.Forms.Label();
|
||||
this.label1 = new System.Windows.Forms.Label();
|
||||
this.label2 = new System.Windows.Forms.Label();
|
||||
this.label3 = new System.Windows.Forms.Label();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// flowPanel
|
||||
//
|
||||
this.flowPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
|
||||
| System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.flowPanel.Location = new System.Drawing.Point(12, 185);
|
||||
this.flowPanel.Name = "flowPanel";
|
||||
this.flowPanel.Size = new System.Drawing.Size(817, 120);
|
||||
this.flowPanel.TabIndex = 0;
|
||||
this.flowPanel.MouseDown += new System.Windows.Forms.MouseEventHandler(this.RemoteControlForm_MouseDown);
|
||||
this.flowPanel.MouseMove += new System.Windows.Forms.MouseEventHandler(this.flowPanel_MouseMove);
|
||||
this.flowPanel.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.flowPanel_PreviewKeyDown);
|
||||
//
|
||||
// btnClose
|
||||
//
|
||||
this.btnClose.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.btnClose.FlatAppearance.BorderColor = System.Drawing.Color.DarkGray;
|
||||
this.btnClose.FlatAppearance.BorderSize = 0;
|
||||
this.btnClose.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
|
||||
this.btnClose.ForeColor = System.Drawing.Color.White;
|
||||
this.btnClose.Location = new System.Drawing.Point(826, 0);
|
||||
this.btnClose.Name = "btnClose";
|
||||
this.btnClose.Size = new System.Drawing.Size(14, 23);
|
||||
this.btnClose.TabIndex = 1;
|
||||
this.btnClose.Text = "x";
|
||||
this.btnClose.UseVisualStyleBackColor = true;
|
||||
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
|
||||
//
|
||||
// lblUC
|
||||
//
|
||||
this.lblUC.AutoSize = true;
|
||||
this.lblUC.ForeColor = System.Drawing.Color.Maroon;
|
||||
this.lblUC.Location = new System.Drawing.Point(12, 0);
|
||||
this.lblUC.Name = "lblUC";
|
||||
this.lblUC.Size = new System.Drawing.Size(100, 13);
|
||||
this.lblUC.TabIndex = 0;
|
||||
this.lblUC.Text = "Under construction!";
|
||||
//
|
||||
// chkDirectMode
|
||||
//
|
||||
this.chkDirectMode.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)));
|
||||
this.chkDirectMode.AutoSize = true;
|
||||
this.chkDirectMode.ForeColor = System.Drawing.Color.White;
|
||||
this.chkDirectMode.Location = new System.Drawing.Point(12, 718);
|
||||
this.chkDirectMode.Name = "chkDirectMode";
|
||||
this.chkDirectMode.Size = new System.Drawing.Size(105, 17);
|
||||
this.chkDirectMode.TabIndex = 2;
|
||||
this.chkDirectMode.Text = "Direct Mode (F1)";
|
||||
this.chkDirectMode.UseVisualStyleBackColor = true;
|
||||
this.chkDirectMode.CheckedChanged += new System.EventHandler(this.chkDirectMode_CheckedChanged);
|
||||
//
|
||||
// pnlMouse
|
||||
//
|
||||
this.pnlMouse.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
|
||||
| System.Windows.Forms.AnchorStyles.Left)
|
||||
| System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.pnlMouse.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
|
||||
this.pnlMouse.Location = new System.Drawing.Point(12, 311);
|
||||
this.pnlMouse.Name = "pnlMouse";
|
||||
this.pnlMouse.Size = new System.Drawing.Size(817, 401);
|
||||
this.pnlMouse.TabIndex = 3;
|
||||
this.pnlMouse.MouseEnter += new System.EventHandler(this.pnlMouse_MouseEnter);
|
||||
this.pnlMouse.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pnlMouse_MouseMove);
|
||||
this.pnlMouse.MouseUp += new System.Windows.Forms.MouseEventHandler(this.pnlMouse_MouseUp);
|
||||
//
|
||||
// lblPos
|
||||
//
|
||||
this.lblPos.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.lblPos.AutoSize = true;
|
||||
this.lblPos.ForeColor = System.Drawing.Color.Maroon;
|
||||
this.lblPos.Location = new System.Drawing.Point(749, 718);
|
||||
this.lblPos.Name = "lblPos";
|
||||
this.lblPos.Size = new System.Drawing.Size(0, 13);
|
||||
this.lblPos.TabIndex = 1;
|
||||
//
|
||||
// label1
|
||||
//
|
||||
this.label1.AutoSize = true;
|
||||
this.label1.ForeColor = System.Drawing.Color.White;
|
||||
this.label1.Location = new System.Drawing.Point(12, 26);
|
||||
this.label1.Name = "label1";
|
||||
this.label1.Size = new System.Drawing.Size(538, 52);
|
||||
this.label1.TabIndex = 4;
|
||||
this.label1.Text = resources.GetString("label1.Text");
|
||||
//
|
||||
// label2
|
||||
//
|
||||
this.label2.AutoSize = true;
|
||||
this.label2.ForeColor = System.Drawing.Color.White;
|
||||
this.label2.Location = new System.Drawing.Point(231, 91);
|
||||
this.label2.Name = "label2";
|
||||
this.label2.Size = new System.Drawing.Size(216, 52);
|
||||
this.label2.TabIndex = 5;
|
||||
this.label2.Text = "Mouse:\r\n- left button: activate/open item\r\n- right button: go back\r\n- wheel: scro" +
|
||||
"ll through menus (only vertically)";
|
||||
//
|
||||
// label3
|
||||
//
|
||||
this.label3.AutoSize = true;
|
||||
this.label3.ForeColor = System.Drawing.Color.White;
|
||||
this.label3.Location = new System.Drawing.Point(12, 91);
|
||||
this.label3.Name = "label3";
|
||||
this.label3.Size = new System.Drawing.Size(180, 91);
|
||||
this.label3.TabIndex = 6;
|
||||
this.label3.Text = "Keyboard keys:\r\n- arrow keys: navigate the menu\r\n- backspace: go back\r\n- escape: " +
|
||||
"exit\r\n- S: open picture settings\r\n- H: open Home\r\n- media keys: volume up/down/m" +
|
||||
"ute";
|
||||
//
|
||||
// RemoteControlForm
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.BackColor = System.Drawing.Color.Black;
|
||||
this.ClientSize = new System.Drawing.Size(841, 735);
|
||||
this.Controls.Add(this.label3);
|
||||
this.Controls.Add(this.label2);
|
||||
this.Controls.Add(this.label1);
|
||||
this.Controls.Add(this.lblPos);
|
||||
this.Controls.Add(this.pnlMouse);
|
||||
this.Controls.Add(this.chkDirectMode);
|
||||
this.Controls.Add(this.lblUC);
|
||||
this.Controls.Add(this.btnClose);
|
||||
this.Controls.Add(this.flowPanel);
|
||||
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
|
||||
this.KeyPreview = true;
|
||||
this.MaximizeBox = false;
|
||||
this.MinimizeBox = false;
|
||||
this.Name = "RemoteControlForm";
|
||||
this.Opacity = 0.8D;
|
||||
this.Text = "RemoteControlForm";
|
||||
this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.RemoteControlForm_FormClosed);
|
||||
this.Load += new System.EventHandler(this.RemoteControlForm_Load);
|
||||
this.Shown += new System.EventHandler(this.RemoteControlForm_Shown);
|
||||
this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.RemoteControlForm_KeyDown);
|
||||
this.KeyUp += new System.Windows.Forms.KeyEventHandler(this.RemoteControlForm_KeyUp);
|
||||
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.RemoteControlForm_MouseDown);
|
||||
this.PreviewKeyDown += new System.Windows.Forms.PreviewKeyDownEventHandler(this.RemoteControlForm_PreviewKeyDown);
|
||||
this.ResumeLayout(false);
|
||||
this.PerformLayout();
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private System.Windows.Forms.FlowLayoutPanel flowPanel;
|
||||
private System.Windows.Forms.Button btnClose;
|
||||
private System.Windows.Forms.Label lblUC;
|
||||
private System.Windows.Forms.CheckBox chkDirectMode;
|
||||
private System.Windows.Forms.Panel pnlMouse;
|
||||
private System.Windows.Forms.Label lblPos;
|
||||
private System.Windows.Forms.Label label1;
|
||||
private System.Windows.Forms.Label label2;
|
||||
private System.Windows.Forms.Label label3;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
using LgTv;
|
||||
using NWin32;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
partial class RemoteControlForm : Form
|
||||
{
|
||||
private LgService _lgService;
|
||||
private List<LgPreset> _buttons;
|
||||
private LgWebOsMouseService _mouseService;
|
||||
private int _maxX, _maxY;
|
||||
private int _posX, _posY;
|
||||
|
||||
public RemoteControlForm(LgService lgService, List<LgPreset> buttons)
|
||||
{
|
||||
_lgService = lgService;
|
||||
_buttons = buttons;
|
||||
|
||||
InitializeComponent();
|
||||
|
||||
pnlMouse.MouseWheel += new MouseEventHandler(pnlMouse_MouseWheel);
|
||||
}
|
||||
|
||||
private void RemoteControlForm_Load(object sender, EventArgs e)
|
||||
{
|
||||
foreach (var preset in _buttons)
|
||||
{
|
||||
var button = new Button();
|
||||
button.ForeColor = Color.White;
|
||||
button.FlatStyle = FlatStyle.Flat;
|
||||
button.FlatAppearance.BorderColor = Color.DarkGray;
|
||||
button.FlatAppearance.MouseOverBackColor = Color.DarkGray;
|
||||
button.Text = preset.name;
|
||||
button.Click += ButtonClick;
|
||||
button.Tag = preset;
|
||||
|
||||
button.Parent = flowPanel;
|
||||
}
|
||||
}
|
||||
|
||||
private void ButtonClick(object sender, EventArgs e)
|
||||
{
|
||||
if (e is MouseEventArgs)
|
||||
{
|
||||
var preset = (LgPreset)(sender as Button).Tag;
|
||||
|
||||
var _ = _lgService.ApplyPreset(preset);
|
||||
}
|
||||
}
|
||||
|
||||
private void btnClose_Click(object sender, EventArgs e)
|
||||
{
|
||||
Close();
|
||||
}
|
||||
|
||||
private void RemoteControlForm_MouseDown(object sender, MouseEventArgs e)
|
||||
{
|
||||
if (e.Button == MouseButtons.Left)
|
||||
{
|
||||
NativeMethods.ReleaseCapture();
|
||||
var intPtr = new UIntPtr(2);
|
||||
NativeMethods.SendMessageW(Handle, NativeConstants.WM_NCLBUTTONDOWN, intPtr, IntPtr.Zero);
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlForm_KeyDown(object sender, KeyEventArgs e)
|
||||
{
|
||||
//var key = e.KeyCode;
|
||||
//HandleKey(key);
|
||||
}
|
||||
|
||||
private void flowPanel_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
|
||||
{
|
||||
//HandleKey(e.KeyCode);
|
||||
}
|
||||
|
||||
private void HandleKey(Keys key)
|
||||
{
|
||||
if (!chkDirectMode.Checked)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var cvt = new KeysConverter();
|
||||
var shortcut = (string)cvt.ConvertTo(key, typeof(string));
|
||||
|
||||
var preset = _buttons.FirstOrDefault(p => p.shortcut != null && p.shortcut.Equals(shortcut));
|
||||
if (preset != null)
|
||||
{
|
||||
var _ = _lgService.ApplyPreset(preset);
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
|
||||
{
|
||||
//HandleKey(e.KeyCode);
|
||||
}
|
||||
|
||||
private void RemoteControlForm_KeyUp(object sender, KeyEventArgs e)
|
||||
{
|
||||
if (e.KeyCode == Keys.F1)
|
||||
{
|
||||
chkDirectMode.Checked = !chkDirectMode.Checked;
|
||||
return;
|
||||
}
|
||||
|
||||
HandleKey(e.KeyCode);
|
||||
}
|
||||
|
||||
private void chkDirectMode_CheckedChanged(object sender, EventArgs e)
|
||||
{
|
||||
if (chkDirectMode.Checked)
|
||||
{
|
||||
// MessageForms.InfoOk(
|
||||
//@"If you enable Direct Mode you will be able to control the TV directly via your keyboard and mouse.
|
||||
//Note that your mouse will be captured in a box and that due to pointer accelaration the control will not be perfect.
|
||||
|
||||
//Keyboard keys:
|
||||
//- arrow keys: navigate the menu
|
||||
//- backspace: go back
|
||||
//- escape: exit
|
||||
//- S: open picture settings
|
||||
//- media keys: volume up/down/mute
|
||||
|
||||
//Mouse:
|
||||
//- left button: activate/open item
|
||||
//- right button: go back
|
||||
//- wheel: scroll through menus (only vertically)
|
||||
|
||||
//Press F1 to stop Direct Mode."
|
||||
// );
|
||||
|
||||
if (_mouseService == null)
|
||||
{
|
||||
_lgService.GetMouseAsync().ContinueWith((task) => BeginInvoke(new Action<Task<LgWebOsMouseService>>(SetMouseService), new[] { task }));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Cursor.Clip = Rectangle.Empty;
|
||||
}
|
||||
}
|
||||
|
||||
private void SetMouseService(Task<LgWebOsMouseService> mouseServiceTask)
|
||||
{
|
||||
_mouseService = mouseServiceTask.Result;
|
||||
|
||||
_maxX = 1920;
|
||||
_maxY = 1080;
|
||||
_posX = _maxX / 2;
|
||||
_posY = _maxY / 2;
|
||||
}
|
||||
|
||||
private void flowPanel_MouseMove(object sender, MouseEventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
private void pnlMouse_MouseEnter(object sender, EventArgs e)
|
||||
{
|
||||
if (chkDirectMode.Checked)
|
||||
{
|
||||
Cursor.Clip = RectangleToScreen(pnlMouse.Bounds);
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlForm_FormClosed(object sender, FormClosedEventArgs e)
|
||||
{
|
||||
Cursor.Clip = Rectangle.Empty;
|
||||
}
|
||||
|
||||
private void pnlMouse_MouseUp(object sender, MouseEventArgs e)
|
||||
{
|
||||
if (chkDirectMode.Checked && _mouseService != null)
|
||||
{
|
||||
if (e.Button == MouseButtons.Left)
|
||||
{
|
||||
_mouseService.Click();
|
||||
}
|
||||
else
|
||||
{
|
||||
HandleKey(Keys.Back);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleMouse(MouseEventArgs e)
|
||||
{
|
||||
if (chkDirectMode.Checked && _mouseService != null)
|
||||
{
|
||||
var scaleX = (double)e.X / pnlMouse.Width;
|
||||
var scaleY = (double)e.Y / pnlMouse.Height;
|
||||
|
||||
var relX = scaleX * _maxX;
|
||||
var relY = scaleY * _maxY;
|
||||
|
||||
var dx = (int)relX - _posX;
|
||||
var dy = (int)relY - _posY;
|
||||
|
||||
_posX = Math.Min(_posX + dx, _maxX);
|
||||
_posY = Math.Min(_posY + dy, _maxY);
|
||||
|
||||
lblPos.Text = $"Pos: {_posX}, {_posY}";
|
||||
|
||||
//var cx = flowPanel.Width / 2;
|
||||
//var cy = flowPanel.Height / 2;
|
||||
|
||||
//var dx = (e.X - cx) / 10;
|
||||
//var dy = (e.Y - cy) / 10;
|
||||
|
||||
_mouseService.Move(dx, dy);
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlForm_Shown(object sender, EventArgs e)
|
||||
{
|
||||
chkDirectMode.Checked = true;
|
||||
}
|
||||
|
||||
private void pnlMouse_MouseMove(object sender, MouseEventArgs e)
|
||||
{
|
||||
HandleMouse(e);
|
||||
}
|
||||
|
||||
private void pnlMouse_MouseWheel(object sender, MouseEventArgs e)
|
||||
{
|
||||
if (chkDirectMode.Checked && _mouseService != null)
|
||||
{
|
||||
var dy = e.Delta * SystemInformation.MouseWheelScrollLines / 120;
|
||||
|
||||
if (dy != 0)
|
||||
{
|
||||
_mouseService.Scroll(0, dy);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="label1.Text" xml:space="preserve">
|
||||
<value>This form allows you to control the TV directly via your keyboard and mouse.
|
||||
Note that your mouse will be captured in a box and that due to pointer acceleration the control will not be perfect.
|
||||
|
||||
Press F1 to stop Direct Mode.</value>
|
||||
</data>
|
||||
</root>
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
partial class RemoteControlPanel
|
||||
{
|
||||
/// <summary>
|
||||
/// Required designer variable.
|
||||
/// </summary>
|
||||
private System.ComponentModel.IContainer components = null;
|
||||
|
||||
/// <summary>
|
||||
/// Clean up any resources being used.
|
||||
/// </summary>
|
||||
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
|
||||
protected override void Dispose(bool disposing)
|
||||
{
|
||||
if (disposing && (components != null))
|
||||
{
|
||||
components.Dispose();
|
||||
}
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
#region Component Designer generated code
|
||||
|
||||
/// <summary>
|
||||
/// Required method for Designer support - do not modify
|
||||
/// the contents of this method with the code editor.
|
||||
/// </summary>
|
||||
private void InitializeComponent()
|
||||
{
|
||||
this.pbRemote = new System.Windows.Forms.PictureBox();
|
||||
this.btnRcDirect = new System.Windows.Forms.Button();
|
||||
((System.ComponentModel.ISupportInitialize)(this.pbRemote)).BeginInit();
|
||||
this.SuspendLayout();
|
||||
//
|
||||
// pbRemote
|
||||
//
|
||||
this.pbRemote.Dock = System.Windows.Forms.DockStyle.Fill;
|
||||
this.pbRemote.Image = global::ColorControl.Properties.Resources.LG_remote;
|
||||
this.pbRemote.Location = new System.Drawing.Point(0, 0);
|
||||
this.pbRemote.Name = "pbRemote";
|
||||
this.pbRemote.Size = new System.Drawing.Size(129, 468);
|
||||
this.pbRemote.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
|
||||
this.pbRemote.TabIndex = 0;
|
||||
this.pbRemote.TabStop = false;
|
||||
this.pbRemote.Click += new System.EventHandler(this.pbRemote_Click);
|
||||
this.pbRemote.MouseMove += new System.Windows.Forms.MouseEventHandler(this.pbRemote_MouseMove);
|
||||
//
|
||||
// btnRcDirect
|
||||
//
|
||||
this.btnRcDirect.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
|
||||
this.btnRcDirect.Location = new System.Drawing.Point(71, 7);
|
||||
this.btnRcDirect.Name = "btnRcDirect";
|
||||
this.btnRcDirect.Size = new System.Drawing.Size(55, 23);
|
||||
this.btnRcDirect.TabIndex = 3;
|
||||
this.btnRcDirect.Text = "Direct";
|
||||
this.btnRcDirect.UseVisualStyleBackColor = true;
|
||||
this.btnRcDirect.Click += new System.EventHandler(this.button1_Click);
|
||||
//
|
||||
// RemoteControlPanel
|
||||
//
|
||||
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
|
||||
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
|
||||
this.BackColor = System.Drawing.Color.White;
|
||||
this.Controls.Add(this.btnRcDirect);
|
||||
this.Controls.Add(this.pbRemote);
|
||||
this.Name = "RemoteControlPanel";
|
||||
this.Size = new System.Drawing.Size(129, 468);
|
||||
this.Load += new System.EventHandler(this.RemoteControlPanel_Load);
|
||||
((System.ComponentModel.ISupportInitialize)(this.pbRemote)).EndInit();
|
||||
this.ResumeLayout(false);
|
||||
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private System.Windows.Forms.PictureBox pbRemote;
|
||||
private System.Windows.Forms.Button btnRcDirect;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Drawing;
|
||||
using System.Linq;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
partial class RemoteControlPanel : UserControl
|
||||
{
|
||||
private static int Range = 35;
|
||||
|
||||
private LgService _lgService;
|
||||
private List<LgPreset> _buttons;
|
||||
private RemoteControlForm _remoteControlForm;
|
||||
private Bitmap _backupImage;
|
||||
private LgPreset _lastHoveredPreset;
|
||||
|
||||
public RemoteControlPanel(LgService lgService, List<LgPreset> buttons)
|
||||
{
|
||||
_lgService = lgService;
|
||||
_buttons = buttons;
|
||||
|
||||
InitializeComponent();
|
||||
|
||||
_backupImage = new Bitmap(pbRemote.Image);
|
||||
|
||||
var txtCoords = Utils.GetResourceFile("RC_coords.txt");
|
||||
|
||||
foreach (var line in txtCoords.Split('\n'))
|
||||
{
|
||||
var columns = line.Split(';');
|
||||
|
||||
var name = columns[0];
|
||||
var preset = _buttons.FirstOrDefault(p => p.name.Equals(name));
|
||||
if (preset != null)
|
||||
{
|
||||
preset.X = int.Parse(columns[1]);
|
||||
preset.Y = int.Parse(columns[2]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void RemoteControlPanel_Load(object sender, EventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
private void ButtonClick(object sender, EventArgs e)
|
||||
{
|
||||
if (e is MouseEventArgs)
|
||||
{
|
||||
var preset = (LgPreset)(sender as Button).Tag;
|
||||
|
||||
var _ = _lgService.ApplyPreset(preset);
|
||||
}
|
||||
}
|
||||
|
||||
private void pbRemote_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (e is MouseEventArgs mouseArgs)
|
||||
{
|
||||
var (posX, posY) = GetCoordsInImage(mouseArgs.X, mouseArgs.Y);
|
||||
|
||||
var preset = _buttons.FirstOrDefault(p => posX >= (p.X - Range) && posX <= (p.X + Range) && posY >= (p.Y - Range) && posY <= (p.Y + Range));
|
||||
|
||||
if (preset != null)
|
||||
{
|
||||
var _ = _lgService.ApplyPreset(preset);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private (int, int) GetCoordsInImage(int curX, int curY)
|
||||
{
|
||||
var width = pbRemote.Width;
|
||||
var aspect = 0.27D;
|
||||
var currentAspect = (double)pbRemote.Width / pbRemote.Height;
|
||||
if (currentAspect > aspect)
|
||||
{
|
||||
width = (int)(aspect * pbRemote.Height);
|
||||
curX = curX - ((pbRemote.Width - width) / 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
var height = (int)(pbRemote.Width / aspect);
|
||||
curY = curY - ((pbRemote.Height - height) / 2);
|
||||
}
|
||||
|
||||
var factor = 405D / width;
|
||||
|
||||
var posX = (int)(curX * factor);
|
||||
var posY = (int)(curY * factor);
|
||||
|
||||
return (posX, posY);
|
||||
}
|
||||
|
||||
private void btnRcDirect_Click(object sender, EventArgs e)
|
||||
{
|
||||
}
|
||||
|
||||
private void pbRemote_MouseMove(object sender, MouseEventArgs mouseArgs)
|
||||
{
|
||||
var (posX, posY) = GetCoordsInImage(mouseArgs.X, mouseArgs.Y);
|
||||
|
||||
var preset = _buttons.FirstOrDefault(p => posX >= (p.X - Range) && posX <= (p.X + Range) && posY >= (p.Y - Range) && posY <= (p.Y + Range));
|
||||
|
||||
var refresh = false;
|
||||
|
||||
if (_lastHoveredPreset != null && (preset == null || preset != _lastHoveredPreset))
|
||||
{
|
||||
var image = (Bitmap)pbRemote.Image;
|
||||
|
||||
for (var y = Math.Max(0, _lastHoveredPreset.Y - Range); y < _lastHoveredPreset.Y + Range; y++)
|
||||
{
|
||||
for (var x = Math.Max(0, _lastHoveredPreset.X - Range); x < _lastHoveredPreset.X + Range; x++)
|
||||
{
|
||||
image.SetPixel(x, y, _backupImage.GetPixel(x, y));
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
refresh = true;
|
||||
}
|
||||
|
||||
if (preset != null && preset != _lastHoveredPreset)
|
||||
{
|
||||
var image = (Bitmap)pbRemote.Image;
|
||||
var rec = new Rectangle(Math.Max(0, preset.X - Range), Math.Max(0, preset.Y - Range), Range * 2, Range * 2);
|
||||
|
||||
using (var g = Graphics.FromImage(image))
|
||||
{
|
||||
using (var cloud_brush = new SolidBrush(Color.FromArgb(128, Color.White)))
|
||||
{
|
||||
g.FillEllipse(cloud_brush, rec);
|
||||
}
|
||||
}
|
||||
|
||||
//for (var y = preset.Y - 30; y < preset.Y + 30; y++)
|
||||
//{
|
||||
// for (var x = preset.X - 30; x < preset.X + 30; x++)
|
||||
// {
|
||||
// var pixel = image.GetPixel(x, y);
|
||||
|
||||
// image.SetPixel(x, y, Color.FromArgb(150, 0, 0));
|
||||
|
||||
// }
|
||||
//}
|
||||
|
||||
refresh = true;
|
||||
}
|
||||
|
||||
if (refresh)
|
||||
{
|
||||
pbRemote.Refresh();
|
||||
}
|
||||
|
||||
_lastHoveredPreset = preset;
|
||||
}
|
||||
|
||||
private void button1_Click(object sender, EventArgs e)
|
||||
{
|
||||
if (_remoteControlForm == null || _remoteControlForm.IsDisposed)
|
||||
{
|
||||
var buttons = _lgService.GetRemoteControlButtons();
|
||||
_remoteControlForm = new RemoteControlForm(_lgService, buttons);
|
||||
_remoteControlForm.Show();
|
||||
}
|
||||
else
|
||||
{
|
||||
_remoteControlForm.Show();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
</root>
|
||||
@@ -0,0 +1,77 @@
|
||||
{
|
||||
"type":"register",
|
||||
"id":"register_0",
|
||||
"payload":{
|
||||
"forcePairing":false,
|
||||
"pairingType":"PROMPT",
|
||||
"client-key":"CLIENTKEYGOESHERE",
|
||||
"manifest":{
|
||||
"manifestVersion":1,
|
||||
"appVersion":"1.1",
|
||||
"signed":{
|
||||
"created":"20140509",
|
||||
"appId":"com.lge.test",
|
||||
"vendorId":"com.lge",
|
||||
"localizedAppNames":{
|
||||
"":"LG Remote App",
|
||||
"ko-KR":"리모컨 앱",
|
||||
"zxx-XX":"ЛГ Rэмotэ AПП"
|
||||
},
|
||||
"localizedVendorNames":{
|
||||
"":"LG Electronics"
|
||||
},
|
||||
"permissions":[
|
||||
"TEST_SECURE",
|
||||
"CONTROL_INPUT_TEXT",
|
||||
"CONTROL_MOUSE_AND_KEYBOARD",
|
||||
"READ_INSTALLED_APPS",
|
||||
"READ_LGE_SDX",
|
||||
"READ_NOTIFICATIONS",
|
||||
"SEARCH",
|
||||
"WRITE_SETTINGS",
|
||||
"WRITE_NOTIFICATION_ALERT",
|
||||
"CONTROL_POWER",
|
||||
"READ_CURRENT_CHANNEL",
|
||||
"READ_RUNNING_APPS",
|
||||
"READ_UPDATE_INFO",
|
||||
"UPDATE_FROM_REMOTE_APP",
|
||||
"READ_LGE_TV_INPUT_EVENTS",
|
||||
"READ_TV_CURRENT_TIME"
|
||||
],
|
||||
"serial":"2f930e2d2cfe083771f68e4fe7bb07"
|
||||
},
|
||||
"permissions":[
|
||||
"LAUNCH",
|
||||
"LAUNCH_WEBAPP",
|
||||
"APP_TO_APP",
|
||||
"CLOSE",
|
||||
"TEST_OPEN",
|
||||
"TEST_PROTECTED",
|
||||
"CONTROL_AUDIO",
|
||||
"CONTROL_DISPLAY",
|
||||
"CONTROL_INPUT_JOYSTICK",
|
||||
"CONTROL_INPUT_MEDIA_RECORDING",
|
||||
"CONTROL_INPUT_MEDIA_PLAYBACK",
|
||||
"CONTROL_INPUT_TV",
|
||||
"CONTROL_POWER",
|
||||
"CONTROL_TV_SCREEN",
|
||||
"READ_APP_STATUS",
|
||||
"READ_CURRENT_CHANNEL",
|
||||
"READ_INPUT_DEVICE_LIST",
|
||||
"READ_NETWORK_STATE",
|
||||
"READ_RUNNING_APPS",
|
||||
"READ_TV_CHANNEL_LIST",
|
||||
"WRITE_NOTIFICATION_TOAST",
|
||||
"READ_POWER_STATE",
|
||||
"READ_COUNTRY_INFO",
|
||||
"READ_SETTINGS"
|
||||
],
|
||||
"signatures":[
|
||||
{
|
||||
"signatureVersion":1,
|
||||
"signature":"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw=="
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 93 KiB |
@@ -0,0 +1,37 @@
|
||||
Power;120;136
|
||||
1;106;228
|
||||
2;196;228
|
||||
3;286;228
|
||||
4;106;296
|
||||
5;196;296
|
||||
6;286;296
|
||||
7;106;362
|
||||
8;196;362
|
||||
9;286;362
|
||||
List;106;425
|
||||
0;196;425
|
||||
SAP;286;425
|
||||
Vol +;98;513
|
||||
Mute;198;513
|
||||
Channel +;298;513
|
||||
Vol -;98;622
|
||||
Channel -;298;622
|
||||
Home;78;695
|
||||
Settings;318;695
|
||||
Up;200;748
|
||||
Left;98;852
|
||||
Enter;200;852
|
||||
Right;304;852
|
||||
Down;200;952
|
||||
Back;80;1000
|
||||
TV Guide;320;1000
|
||||
Netflix;92;1076
|
||||
Inputs;200;1066
|
||||
Amazon Prime;312;1076
|
||||
Red;90;1150
|
||||
Green;164;1150
|
||||
Yellow;240;1150
|
||||
Blue;316;1150
|
||||
Rakuten TV;116;1218
|
||||
Play;202;1218
|
||||
Pause;291;1218
|
||||
@@ -9,7 +9,8 @@ namespace ColorControl
|
||||
public class RestartDetector : IDisposable
|
||||
{
|
||||
public bool RestartDetected { get; private set; }
|
||||
|
||||
public bool PowerOffDetected { get; private set; }
|
||||
|
||||
private EventLogWatcher watcher = null;
|
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
@@ -17,8 +18,7 @@ namespace ColorControl
|
||||
{
|
||||
try
|
||||
{
|
||||
EventLogQuery subscriptionQuery = new EventLogQuery(
|
||||
"System", PathType.LogName, "*[System[Provider[@Name='USER32'] and (EventID=1074)]]");
|
||||
EventLogQuery subscriptionQuery = new EventLogQuery("System", PathType.LogName, "*[System[Provider[@Name='USER32'] and (EventID=1074)]]");
|
||||
|
||||
watcher = new EventLogWatcher(subscriptionQuery);
|
||||
|
||||
@@ -32,7 +32,7 @@ namespace ColorControl
|
||||
// Activate the subscription
|
||||
watcher.Enabled = true;
|
||||
}
|
||||
catch (EventLogReadingException e)
|
||||
catch (EventLogReadingException)
|
||||
{
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,7 @@ namespace ColorControl
|
||||
public void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
|
||||
{
|
||||
RestartDetected = false;
|
||||
PowerOffDetected = false;
|
||||
try
|
||||
{
|
||||
Logger.Debug("Logging event: " + arg);
|
||||
@@ -60,28 +61,16 @@ namespace ColorControl
|
||||
{
|
||||
RestartDetected = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (x.Value.Equals("power off"))
|
||||
{
|
||||
PowerOffDetected = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//if (arg.EventRecord != null)
|
||||
//{
|
||||
// String[] xPathRefs = new String[1];
|
||||
// xPathRefs[0] = "Event/EventData/Data";
|
||||
// IEnumerable<String> xPathEnum = xPathRefs;
|
||||
|
||||
// EventLogPropertySelector logPropertyContext = new EventLogPropertySelector(xPathEnum);
|
||||
// IList<object> logEventProps = ((EventLogRecord)arg.EventRecord).GetPropertyValues(logPropertyContext);
|
||||
|
||||
// string[] eventData = (string[])logEventProps[0];
|
||||
|
||||
// foreach (string attribute in eventData)
|
||||
// {
|
||||
// if (attribute.Contains("restart")) { restart = true; break; }
|
||||
// }
|
||||
//}
|
||||
}
|
||||
catch (Exception e)
|
||||
catch (Exception)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
abstract class ServiceBase<T> where T : PresetBase
|
||||
{
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public event EventHandler<T> AfterApplyPreset;
|
||||
|
||||
protected string _dataPath;
|
||||
protected string _presetsBaseFilename;
|
||||
protected string _presetsFilename;
|
||||
protected string _presetsBackupFilename;
|
||||
protected bool _initialized = false;
|
||||
protected List<T> _presets;
|
||||
protected T _lastAppliedPreset;
|
||||
protected string _loadPresetsError;
|
||||
private List<JsonConverter> _jsonConverters;
|
||||
|
||||
public ServiceBase(string dataPath, string presetsBaseFilename)
|
||||
{
|
||||
_dataPath = dataPath;
|
||||
_presetsBaseFilename = presetsBaseFilename;
|
||||
_jsonConverters = new List<JsonConverter>();
|
||||
|
||||
Initialize();
|
||||
}
|
||||
|
||||
~ServiceBase()
|
||||
{
|
||||
Uninitialize();
|
||||
}
|
||||
|
||||
public List<T> GetPresets()
|
||||
{
|
||||
return _presets;
|
||||
}
|
||||
|
||||
public T GetPresetByIdOrName(string idOrName)
|
||||
{
|
||||
var preset = _presets.FirstOrDefault(p => p.name != null && p.name.Equals(idOrName, StringComparison.OrdinalIgnoreCase));
|
||||
if (preset == null && int.TryParse(idOrName, out var id))
|
||||
{
|
||||
preset = _presets.FirstOrDefault(p => p.id == id);
|
||||
}
|
||||
|
||||
return preset;
|
||||
}
|
||||
|
||||
public T GetLastAppliedPreset()
|
||||
{
|
||||
return _lastAppliedPreset;
|
||||
}
|
||||
|
||||
protected virtual void Initialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
protected virtual void Uninitialize()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
protected void PresetApplied()
|
||||
{
|
||||
AfterApplyPreset?.Invoke(this, _lastAppliedPreset);
|
||||
}
|
||||
|
||||
protected void LoadPresets()
|
||||
{
|
||||
_presetsFilename = Path.Combine(_dataPath, _presetsBaseFilename);
|
||||
_presetsBackupFilename = Path.Combine(_dataPath, $"{_presetsBaseFilename}.backup");
|
||||
|
||||
try
|
||||
{
|
||||
var presetsExists = File.Exists(_presetsFilename);
|
||||
if (presetsExists)
|
||||
{
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(_presetsFilename);
|
||||
|
||||
// Hack to convert incorrect triggers
|
||||
json = json.Replace(@"""Triggers"":0", @"""Triggers"":[]");
|
||||
|
||||
_presets = JsonConvert.DeserializeObject<List<T>>(json, _jsonConverters.ToArray());
|
||||
|
||||
if (_presets != null)
|
||||
{
|
||||
if (File.Exists(_presetsBackupFilename))
|
||||
{
|
||||
File.Delete(_presetsBackupFilename);
|
||||
}
|
||||
File.Copy(_presetsFilename, _presetsBackupFilename);
|
||||
}
|
||||
}
|
||||
catch (Exception ex1)
|
||||
{
|
||||
Logger.Error($"Error while loading presets, reverting to default presets: {ex1.Message}");
|
||||
_loadPresetsError = ex1.Message;
|
||||
}
|
||||
}
|
||||
if (!presetsExists || _presets == null)
|
||||
{
|
||||
Logger.Debug("Reverting to default presets");
|
||||
try
|
||||
{
|
||||
_presets = GetDefaultPresets();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error($"Error loading default presets, reverting to empty list: {e.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"General error while loading presets, reverting to empty list: {ex.Message}");
|
||||
_loadPresetsError = ex.Message;
|
||||
}
|
||||
if (_presets == null)
|
||||
{
|
||||
_presets = new List<T>();
|
||||
}
|
||||
}
|
||||
|
||||
protected abstract List<T> GetDefaultPresets();
|
||||
|
||||
protected void AddJsonConverter(JsonConverter jsonConverter)
|
||||
{
|
||||
_jsonConverters.Add(jsonConverter);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,16 +7,59 @@ namespace ColorControl
|
||||
public const string RunningFromScheduledTaskParam = "--scheduled";
|
||||
public const string ActivateChromeFontFixParam = "--activate-chrome-font-fix";
|
||||
public const string DeactivateChromeFontFixParam = "--deactivate-chrome-font-fix";
|
||||
public const string ExecuteHelpParam = "--help";
|
||||
public const string ExecuteNvidiaPresetParam = "--nvpreset";
|
||||
public const string ExecuteAmdPresetParam = "--amdpreset";
|
||||
public const string ExecuteLgPresetParam = "--lgpreset";
|
||||
public const string NoGuiParam = "--nogui";
|
||||
public const string EnableAutoStartParam = "--enable-auto-start";
|
||||
public const string DisableAutoStartParam = "--disable-auto-start";
|
||||
|
||||
public bool RunningFromScheduledTask { get; private set; }
|
||||
public bool ActivateChromeFontFix { get; private set; }
|
||||
public bool DeactivateChromeFontFix { get; private set; }
|
||||
public bool ExecuteHelp { get; private set; }
|
||||
public bool ExecuteNvidiaPreset { get; private set; }
|
||||
public string NvidiaPresetIdOrName { get; private set; }
|
||||
public bool ExecuteAmdPreset { get; private set; }
|
||||
public string AmdPresetIdOrName { get; private set; }
|
||||
public bool ExecuteLgPreset { get; private set; }
|
||||
public string LgPresetName { get; private set; }
|
||||
public bool NoGui { get; set; }
|
||||
public bool EnableAutoStart { get; private set; }
|
||||
public bool DisableAutoStart { get; private set; }
|
||||
|
||||
public static StartUpParams Parse(IEnumerable<string> args)
|
||||
{
|
||||
var settings = new StartUpParams();
|
||||
var parseNameParam = string.Empty;
|
||||
foreach (var arg in args)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(parseNameParam))
|
||||
{
|
||||
switch (parseNameParam)
|
||||
{
|
||||
case ExecuteNvidiaPresetParam:
|
||||
{
|
||||
settings.NvidiaPresetIdOrName = arg;
|
||||
break;
|
||||
}
|
||||
case ExecuteAmdPresetParam:
|
||||
{
|
||||
settings.AmdPresetIdOrName = arg;
|
||||
break;
|
||||
}
|
||||
case ExecuteLgPresetParam:
|
||||
{
|
||||
settings.LgPresetName = arg;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
parseNameParam = string.Empty;
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (arg.ToLowerInvariant())
|
||||
{
|
||||
case RunningFromScheduledTaskParam:
|
||||
@@ -34,6 +77,45 @@ namespace ColorControl
|
||||
settings.DeactivateChromeFontFix = true;
|
||||
break;
|
||||
}
|
||||
case ExecuteHelpParam:
|
||||
{
|
||||
settings.ExecuteHelp = true;
|
||||
settings.NoGui = true;
|
||||
break;
|
||||
}
|
||||
case ExecuteNvidiaPresetParam:
|
||||
{
|
||||
settings.ExecuteNvidiaPreset = true;
|
||||
parseNameParam = ExecuteNvidiaPresetParam;
|
||||
break;
|
||||
}
|
||||
case ExecuteAmdPresetParam:
|
||||
{
|
||||
settings.ExecuteAmdPreset = true;
|
||||
parseNameParam = ExecuteAmdPresetParam;
|
||||
break;
|
||||
}
|
||||
case ExecuteLgPresetParam:
|
||||
{
|
||||
settings.ExecuteLgPreset = true;
|
||||
parseNameParam = ExecuteLgPresetParam;
|
||||
break;
|
||||
}
|
||||
case NoGuiParam:
|
||||
{
|
||||
settings.NoGui = true;
|
||||
break;
|
||||
}
|
||||
case EnableAutoStartParam:
|
||||
{
|
||||
settings.EnableAutoStart = true;
|
||||
break;
|
||||
}
|
||||
case DisableAutoStartParam:
|
||||
{
|
||||
settings.DisableAutoStart = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return settings;
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Web.Script.Serialization;
|
||||
using System.Windows.Forms;
|
||||
|
||||
namespace ColorControl
|
||||
@@ -19,7 +14,6 @@ namespace ColorControl
|
||||
|
||||
public static TreeNode CreateTree(object obj, string text)
|
||||
{
|
||||
JavaScriptSerializer jss = new JavaScriptSerializer();
|
||||
var serialized = JsonConvert.SerializeObject(obj, Formatting.None,
|
||||
new JsonSerializerSettings {
|
||||
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
|
||||
@@ -30,7 +24,7 @@ namespace ColorControl
|
||||
},
|
||||
Converters = new [] { new Newtonsoft.Json.Converters.StringEnumConverter() }
|
||||
});
|
||||
Dictionary<string, object> dic = jss.Deserialize<Dictionary<string, object>>(serialized);
|
||||
var dic = JsonConvert.DeserializeObject<Dictionary<string, object>>(serialized);
|
||||
var root = new TreeNode();
|
||||
root.Text = text;
|
||||
BuildTree(dic, root);
|
||||
@@ -48,9 +42,9 @@ namespace ColorControl
|
||||
node.Nodes.Add(keyValueNode);
|
||||
BuildTree(kv.Value, keyValueNode);
|
||||
}
|
||||
else if (item is ArrayList)
|
||||
else if (item.GetType() == typeof(JArray))
|
||||
{
|
||||
ArrayList list = (ArrayList)item;
|
||||
var list = (JArray)item;
|
||||
int index = 0;
|
||||
foreach (object value in list)
|
||||
{
|
||||
@@ -70,6 +64,14 @@ namespace ColorControl
|
||||
BuildTree(d, node);
|
||||
}
|
||||
}
|
||||
else if (item.GetType() == typeof(JObject))
|
||||
{
|
||||
var jobject = item as JObject;
|
||||
foreach (var property in jobject.Properties())
|
||||
{
|
||||
BuildTree(new KeyValuePair<string, object>(property.Name, property.Value), node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static string GetValueAsString(object value)
|
||||
@@ -82,13 +84,13 @@ namespace ColorControl
|
||||
return "[]";
|
||||
}
|
||||
|
||||
if (value is ArrayList)
|
||||
if (value.GetType() == typeof(JArray))
|
||||
{
|
||||
var arr = value as ArrayList;
|
||||
var arr = value as JArray;
|
||||
return $"[{arr.Count}]";
|
||||
}
|
||||
|
||||
if (type.IsGenericType)
|
||||
if (type.IsGenericType || value.GetType() == typeof(JObject))
|
||||
{
|
||||
return "{}";
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using Microsoft.Win32;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
static class UserSessionInfo
|
||||
{
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public static bool UserLocalSession { get; private set; } = true;
|
||||
public static SessionSwitchReason LastSessionSwitchReason { get; private set; } = 0;
|
||||
|
||||
public delegate void UserSessionSwitchHandler(bool toLocal);
|
||||
public static event UserSessionSwitchHandler UserSessionSwitch;
|
||||
|
||||
public static void Install()
|
||||
{
|
||||
SystemEvents.SessionSwitch += SessionSwitchHandler;
|
||||
}
|
||||
|
||||
public static void SessionSwitchHandler(object sender, SessionSwitchEventArgs evt)
|
||||
{
|
||||
if (evt.Reason == SessionSwitchReason.ConsoleDisconnect)
|
||||
{
|
||||
Logger.Debug("Detected a disconnect from the console");
|
||||
UserLocalSession = false;
|
||||
UserSessionSwitch(false);
|
||||
}
|
||||
else if (evt.Reason == SessionSwitchReason.ConsoleConnect)
|
||||
{
|
||||
Logger.Debug("Detected a connect to the console");
|
||||
if (!UserLocalSession)
|
||||
{
|
||||
Logger.Debug("Session state switched to local");
|
||||
UserLocalSession = true;
|
||||
UserSessionSwitch(true);
|
||||
}
|
||||
}
|
||||
LastSessionSwitchReason = evt.Reason;
|
||||
}
|
||||
}
|
||||
}
|
||||
+859
-15
@@ -1,11 +1,22 @@
|
||||
using Microsoft.Win32;
|
||||
using Microsoft.Win32.TaskScheduler;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using NStandard;
|
||||
using NWin32;
|
||||
using NWin32.NativeTypes;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.Diagnostics;
|
||||
using System.Drawing;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Security.Principal;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Forms;
|
||||
@@ -14,7 +25,7 @@ using Windows.Devices.Enumeration.Pnp;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class Utils
|
||||
static class Utils
|
||||
{
|
||||
[Flags]
|
||||
public enum ModKeys : int
|
||||
@@ -25,15 +36,80 @@ namespace ColorControl
|
||||
Win = 8
|
||||
}
|
||||
|
||||
public static string PKEY_PNPX_IpAddress = "{656a3bb3-ecc0-43fd-8477-4ae0404a96cd} 12297";
|
||||
public static string PKEY_PNPX_PhysicalAddress = "{656a3bb3-ecc0-43fd-8477-4ae0404a96cd} 12294";
|
||||
public enum UserNotificationState : int
|
||||
{
|
||||
QUNS_NOT_PRESENT = 1,
|
||||
QUNS_BUSY,
|
||||
QUNS_RUNNING_D3D_FULL_SCREEN,
|
||||
QUNS_PRESENTATION_MODE,
|
||||
QUNS_ACCEPTS_NOTIFICATIONS,
|
||||
QUNS_QUIET_TIME,
|
||||
QUNS_APP
|
||||
}
|
||||
|
||||
public static UserNotificationState[] NotificationsDisabledStates = new[] {
|
||||
UserNotificationState.QUNS_BUSY,
|
||||
UserNotificationState.QUNS_RUNNING_D3D_FULL_SCREEN,
|
||||
UserNotificationState.QUNS_PRESENTATION_MODE,
|
||||
};
|
||||
|
||||
public const int WM_BRINGTOFRONT = NativeConstants.WM_USER + 1;
|
||||
|
||||
public const int ENUM_CURRENT_SETTINGS = -1;
|
||||
public const int ENUM_REGISTRY_SETTINGS = -2;
|
||||
|
||||
public static string PKEY_PNPX_IpAddress = "{656a3bb3-ecc0-43fd-8477-4ae0404a96cd} 12297";
|
||||
public static string PKEY_PNPX_PhysicalAddress = "{656a3bb3-ecc0-43fd-8477-4ae0404a96cd} 12294";
|
||||
|
||||
public delegate void PCREATE_PROCESS_NOTIFY_ROUTINE(IntPtr ParentId, IntPtr ProcessId, bool Create);
|
||||
|
||||
public static bool ConsoleOpened { get; private set; }
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
public static extern bool RegisterHotKey(IntPtr hWnd, int id, int fsModifiers, int vlc);
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public extern static bool ShutdownBlockReasonCreate(IntPtr hWnd, [MarshalAs(UnmanagedType.LPWStr)] string pwszReason);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public extern static bool ShutdownBlockReasonDestroy(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
public static extern bool EnumDisplaySettingsA(string deviceName, int modeNum, out DEVMODEA devMode);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool AllocConsole();
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
|
||||
private static extern bool AttachConsole(int processId);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
[return: MarshalAs(UnmanagedType.Bool)]
|
||||
public static extern bool FreeConsole();
|
||||
|
||||
[DllImport("shell32.dll")]
|
||||
public static extern int SHQueryUserNotificationState(out UserNotificationState pquns);
|
||||
|
||||
[DllImport("user32.dll", SetLastError = true)]
|
||||
public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
|
||||
|
||||
//[DllImport("Wtsapi32.dll")]
|
||||
//public extern static bool WTSRegisterSessionNotification(IntPtr hWnd, uint dwFlags);
|
||||
|
||||
//[DllImport("Wtsapi32.dll")]
|
||||
//public extern static bool WTSUnRegisterSessionNotification(IntPtr hWnd);
|
||||
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
private static bool WinKeyDown = false;
|
||||
private static UserNotificationState LastNotificationState;
|
||||
private static Keys[] KeysWithoutModifiers = new[] { Keys.F13, Keys.F14, Keys.F15, Keys.F16, Keys.F17, Keys.F18, Keys.F19, Keys.F20, Keys.F21, Keys.F22, Keys.F23, Keys.F24 };
|
||||
|
||||
public static Bitmap SubPixelShift(Bitmap bitmap)
|
||||
{
|
||||
Bitmap bitmap2 = (Bitmap) bitmap.Clone();
|
||||
Bitmap bitmap2 = (Bitmap)bitmap.Clone();
|
||||
|
||||
int shift = -1;
|
||||
bool shiftRed = true;
|
||||
@@ -126,9 +202,10 @@ namespace ColorControl
|
||||
|
||||
internal static bool ExecuteElevated(string args)
|
||||
{
|
||||
var info = new ProcessStartInfo(Assembly.GetEntryAssembly().Location, args)
|
||||
var info = new ProcessStartInfo(Process.GetCurrentProcess().MainModule.FileName, args)
|
||||
{
|
||||
Verb = "runas", // indicates to elevate privileges
|
||||
UseShellExecute = true,
|
||||
};
|
||||
|
||||
var process = new Process
|
||||
@@ -188,6 +265,21 @@ namespace ColorControl
|
||||
return key != null;
|
||||
}
|
||||
|
||||
internal static void GetRegistryKeyValue(string keyname, string valueName, bool deepSearch = false)
|
||||
{
|
||||
var key = Registry.LocalMachine.OpenSubKey(keyname);
|
||||
|
||||
foreach (var subKeyName in key.GetSubKeyNames())
|
||||
{
|
||||
var subKey = key.OpenSubKey(subKeyName);
|
||||
if (subKey.GetValueNames().Contains(valueName))
|
||||
{
|
||||
Thread.Sleep(0);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
internal static bool UpdateShortcut(string path, string arguments, bool removeArguments = false)
|
||||
{
|
||||
if (File.Exists(path))
|
||||
@@ -219,10 +311,10 @@ namespace ColorControl
|
||||
object objValue;
|
||||
string value = null;
|
||||
|
||||
foreach (var key in device.Properties.Keys)
|
||||
{
|
||||
Debug.WriteLine(key);
|
||||
}
|
||||
//foreach (var key in device.Properties.Keys)
|
||||
//{
|
||||
// Debug.WriteLine(key);
|
||||
//}
|
||||
|
||||
if (device.Properties.TryGetValue(propertyName, out objValue))
|
||||
{
|
||||
@@ -253,9 +345,11 @@ namespace ColorControl
|
||||
|
||||
var list = await DeviceInformation.FindAllAsync("", new List<string>());
|
||||
|
||||
var reqs = new List<string>();
|
||||
reqs.Add(PKEY_PNPX_IpAddress);
|
||||
reqs.Add(PKEY_PNPX_PhysicalAddress);
|
||||
var reqs = new List<string>
|
||||
{
|
||||
PKEY_PNPX_IpAddress,
|
||||
PKEY_PNPX_PhysicalAddress
|
||||
};
|
||||
|
||||
foreach (var dev in list)
|
||||
{
|
||||
@@ -284,11 +378,21 @@ namespace ColorControl
|
||||
return devices;
|
||||
}
|
||||
|
||||
public static void WaitForTask(Task task)
|
||||
public static T WaitForTask<T>(Task<T> task)
|
||||
{
|
||||
while (task != null && (task.Status < TaskStatus.WaitingForChildrenToComplete))
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
Thread.Sleep(10);
|
||||
Application.DoEvents();
|
||||
}
|
||||
return task.Result;
|
||||
}
|
||||
|
||||
public static void WaitForTask(System.Threading.Tasks.Task task)
|
||||
{
|
||||
while (task != null && (task.Status < TaskStatus.WaitingForChildrenToComplete))
|
||||
{
|
||||
Thread.Sleep(10);
|
||||
Application.DoEvents();
|
||||
}
|
||||
}
|
||||
@@ -302,5 +406,745 @@ namespace ColorControl
|
||||
if ((bool)t.GetField("added", hidden).GetValue(ni))
|
||||
t.GetMethod("UpdateIcon", hidden).Invoke(ni, new object[] { true });
|
||||
}
|
||||
|
||||
internal static Image GenerateGradientBitmap(int width, int height)
|
||||
{
|
||||
var bitmap = new Bitmap(512, height);
|
||||
|
||||
for (var i = 0; i < 256; i++)
|
||||
{
|
||||
var pixel = Color.FromArgb(i, i, i);
|
||||
|
||||
for (var h = 0; h < height; h++)
|
||||
{
|
||||
bitmap.SetPixel(i * 2, h, pixel);
|
||||
bitmap.SetPixel(i * 2 + 1, h, pixel);
|
||||
}
|
||||
}
|
||||
|
||||
return bitmap;
|
||||
}
|
||||
|
||||
public static string FirstCharUpperCase(string name)
|
||||
{
|
||||
return name.Substring(0, 1).ToUpper() + name.Substring(1);
|
||||
}
|
||||
|
||||
public static string GetDescriptionByEnumName<T>(string value) where T : IConvertible
|
||||
{
|
||||
string description = null;
|
||||
|
||||
if (Enum.TryParse(typeof(T), value, out var result))
|
||||
{
|
||||
description = (result as IConvertible)?.GetDescription();
|
||||
}
|
||||
|
||||
description = description ?? FirstCharUpperCase(value);
|
||||
|
||||
return description;
|
||||
}
|
||||
|
||||
public static string GetDescription<T>(this T e) where T : IConvertible
|
||||
{
|
||||
return GetDescription(e.GetType(), e);
|
||||
}
|
||||
|
||||
public static string GetDescription(Type enumType, IConvertible value)
|
||||
{
|
||||
if (enumType.BaseType == typeof(Enum))
|
||||
{
|
||||
var val = value.ToInt32(CultureInfo.InvariantCulture);
|
||||
|
||||
var enumName = enumType.GetEnumName(val);
|
||||
if (enumName == null)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
var memInfo = enumType.GetMember(enumName);
|
||||
var descriptionAttribute = memInfo[0]
|
||||
.GetCustomAttributes(typeof(DescriptionAttribute), false)
|
||||
.FirstOrDefault() as DescriptionAttribute;
|
||||
|
||||
if (descriptionAttribute != null)
|
||||
{
|
||||
return descriptionAttribute.Description;
|
||||
}
|
||||
}
|
||||
|
||||
return null; // could also return string.Empty
|
||||
}
|
||||
|
||||
public static string GetEnumNameByDescription(Type enumType, string description)
|
||||
{
|
||||
if (enumType.BaseType == typeof(Enum))
|
||||
{
|
||||
foreach (var enumValue in Enum.GetValues(enumType))
|
||||
{
|
||||
if (description.Equals(GetDescription(enumType, enumValue as IConvertible), StringComparison.Ordinal))
|
||||
{
|
||||
return Enum.GetName(enumType, enumValue);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null; // could also return string.Empty
|
||||
}
|
||||
|
||||
public static List<string> GetDescriptions<T>(int value = -1, int fromValue = 0) where T : IConvertible
|
||||
{
|
||||
return GetDescriptions(typeof(T), value, fromValue);
|
||||
}
|
||||
|
||||
public static List<string> GetDescriptions(Type enumType, int value = -1, int fromValue = 0)
|
||||
{
|
||||
var list = new List<string>();
|
||||
foreach (var enumValue in Enum.GetValues(enumType))
|
||||
{
|
||||
if ((int)enumValue < fromValue || value >= 0 && ((int)enumValue & value) == 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
list.Add(GetDescription(enumType, enumValue as IConvertible));
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static void RegisterTask(string taskName, bool enabled)
|
||||
{
|
||||
var file = Process.GetCurrentProcess().MainModule.FileName;
|
||||
var directory = Path.GetDirectoryName(file);
|
||||
|
||||
try
|
||||
{
|
||||
using (TaskService ts = new TaskService())
|
||||
{
|
||||
if (enabled)
|
||||
{
|
||||
TaskDefinition td = ts.NewTask();
|
||||
td.RegistrationInfo.Description = "Start ColorControl";
|
||||
|
||||
td.Triggers.Add(new LogonTrigger { UserId = WindowsIdentity.GetCurrent().Name });
|
||||
|
||||
td.Actions.Add(new ExecAction(file, StartUpParams.RunningFromScheduledTaskParam, directory));
|
||||
|
||||
ts.RootFolder.RegisterTaskDefinition(taskName, td);
|
||||
}
|
||||
else
|
||||
{
|
||||
ts.RootFolder.DeleteTask(taskName, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
MessageForms.ErrorOk("Could not create/delete task: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool TaskExists(string taskName, bool update)
|
||||
{
|
||||
var file = Assembly.GetExecutingAssembly().Location;
|
||||
using (TaskService ts = new TaskService())
|
||||
{
|
||||
var task = ts.RootFolder.Tasks.FirstOrDefault(x => x.Name.Equals(taskName));
|
||||
|
||||
if (task != null)
|
||||
{
|
||||
//var action = task.Definition.Actions.FirstOrDefault(x => x.ActionType == TaskActionType.Execute);
|
||||
//if (action != null)
|
||||
//{
|
||||
// var execAction = action as ExecAction;
|
||||
// if (!execAction.Path.Equals(file))
|
||||
// {
|
||||
// RegisterTask(taskName, false);
|
||||
// RegisterTask(taskName, true);
|
||||
// }
|
||||
//}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool RegisterShortcut(IntPtr handle, int id, string shortcut, bool clear = false)
|
||||
{
|
||||
if (clear)
|
||||
{
|
||||
UnregisterHotKey(handle, id);
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(shortcut))
|
||||
{
|
||||
var (mods, key) = ParseShortcut(shortcut);
|
||||
var result = RegisterHotKey(handle, id, mods, key);
|
||||
if (!result)
|
||||
{
|
||||
var errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
|
||||
Logger.Error($"Could not register shortcut {shortcut}: {errorMessage}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static ToolStripMenuItem BuildDropDownMenuEx(ContextMenuStrip mnuParent, string name, Type enumType, EventHandler clickEvent, object tag = null, int min = 0, int max = 0)
|
||||
{
|
||||
var subMenuName = $"{mnuParent.Name}_{name}";
|
||||
var subMenuItems = mnuParent.Items.Find(subMenuName, false);
|
||||
|
||||
if (subMenuItems.Length > 0)
|
||||
{
|
||||
return subMenuItems[0] as ToolStripMenuItem;
|
||||
}
|
||||
|
||||
ToolStripMenuItem subMenuItem;
|
||||
subMenuItem = (ToolStripMenuItem)mnuParent.Items.Add(name);
|
||||
subMenuItem.Name = subMenuName;
|
||||
|
||||
if (enumType != null)
|
||||
{
|
||||
foreach (var enumValue in Enum.GetValues(enumType))
|
||||
{
|
||||
var itemText = (enumValue as IConvertible).GetDescription() ?? enumValue.ToString();
|
||||
var item = subMenuItem.DropDownItems.Add(itemText);
|
||||
item.Tag = tag;
|
||||
var strValue = enumValue.ToString();
|
||||
if (strValue.EndsWith("_"))
|
||||
{
|
||||
strValue = strValue.Substring(0, strValue.Length - 1);
|
||||
}
|
||||
item.AccessibleName = strValue;
|
||||
item.Click += clickEvent;
|
||||
}
|
||||
}
|
||||
else if (min >= 0 && max > min)
|
||||
{
|
||||
for (var i = 0; i <= 10; i++)
|
||||
{
|
||||
var value = i * (max / 10);
|
||||
|
||||
var subSubItemName = $"{subMenuName}_{value}";
|
||||
|
||||
var item = subMenuItem.DropDownItems.Add(value.ToString());
|
||||
item.Name = subSubItemName;
|
||||
item.Tag = tag;
|
||||
item.Click += clickEvent;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
subMenuItem.Tag = tag;
|
||||
subMenuItem.Click += clickEvent;
|
||||
}
|
||||
|
||||
return subMenuItem;
|
||||
}
|
||||
|
||||
public static void BuildDropDownMenu(ToolStripDropDownItem mnuParent, string name, Type enumType, object colorData, string propertyName, EventHandler clickEvent)
|
||||
{
|
||||
PropertyInfo property = null;
|
||||
var subMenuItems = mnuParent.DropDownItems.Find("miColorSettings_" + name, false);
|
||||
ToolStripMenuItem subMenuItem;
|
||||
if (subMenuItems.Length == 0)
|
||||
{
|
||||
subMenuItem = (ToolStripMenuItem)mnuParent.DropDownItems.Add(name);
|
||||
subMenuItem.Name = "miColorSettings_" + name;
|
||||
|
||||
if (colorData != null)
|
||||
{
|
||||
property = colorData.GetType().GetDeclaredProperty(propertyName);
|
||||
subMenuItem.Tag = property;
|
||||
}
|
||||
|
||||
foreach (var enumValue in Enum.GetValues(enumType))
|
||||
{
|
||||
var item = subMenuItem.DropDownItems.Add(enumValue.ToString());
|
||||
item.Tag = enumValue;
|
||||
item.Click += clickEvent;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
subMenuItem = (ToolStripMenuItem)subMenuItems[0];
|
||||
property = (PropertyInfo)subMenuItem.Tag;
|
||||
}
|
||||
|
||||
if (colorData == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
var value = property.GetValue(colorData);
|
||||
|
||||
foreach (var item in subMenuItem.DropDownItems)
|
||||
{
|
||||
if (item is ToolStripMenuItem)
|
||||
{
|
||||
var menuItem = (ToolStripMenuItem)item;
|
||||
if (menuItem.Tag != null)
|
||||
{
|
||||
menuItem.Checked = menuItem.Tag.Equals(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static void BuildComboBox<T>(ComboBox comboBox, params T[] skip) where T : IConvertible
|
||||
{
|
||||
if (comboBox.Items.Count == 0)
|
||||
{
|
||||
foreach (var enumValue in Enum.GetValues(typeof(T)))
|
||||
{
|
||||
if (skip.Contains((T)enumValue))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
var item = new EnumComboBoxItem
|
||||
{
|
||||
Name = ((T)enumValue).GetDescription(),
|
||||
Id = (int)enumValue
|
||||
};
|
||||
|
||||
comboBox.Items.Add(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static int SetComboBoxEnumIndex(ComboBox comboBox, int value)
|
||||
{
|
||||
if (comboBox.Items.Count == 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
var index = 0;
|
||||
|
||||
for (var i = 0; i < comboBox.Items.Count; i++)
|
||||
{
|
||||
var item = comboBox.Items[i] as EnumComboBoxItem;
|
||||
if (item.Id == value)
|
||||
{
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
comboBox.SelectedIndex = index;
|
||||
|
||||
return index;
|
||||
}
|
||||
|
||||
public static T GetComboBoxEnumItem<T>(ComboBox comboBox) where T : IConvertible
|
||||
{
|
||||
if (comboBox.SelectedIndex == -1)
|
||||
{
|
||||
return (T)Enum.Parse(typeof(T), "None");
|
||||
}
|
||||
|
||||
var item = comboBox.SelectedItem as EnumComboBoxItem;
|
||||
|
||||
return (T)Enum.Parse(typeof(T), item.Id.ToString());
|
||||
}
|
||||
|
||||
public static string FormatKeyboardShortcut(KeyEventArgs keyEvent)
|
||||
{
|
||||
var pressedModifiers = keyEvent.Modifiers;
|
||||
|
||||
//Debug.WriteLine("KD: " + e.Modifiers + ", " + e.KeyCode);
|
||||
|
||||
var shortcutString = (pressedModifiers > 0 ? pressedModifiers.ToString() : "");
|
||||
if (keyEvent.KeyCode == Keys.LWin || WinKeyDown)
|
||||
{
|
||||
WinKeyDown = true;
|
||||
if (!string.IsNullOrEmpty(shortcutString))
|
||||
{
|
||||
shortcutString += ", ";
|
||||
}
|
||||
shortcutString += "Win";
|
||||
}
|
||||
|
||||
var empty = string.IsNullOrEmpty(shortcutString);
|
||||
if ((!empty || KeysWithoutModifiers.Contains(keyEvent.KeyCode)) && keyEvent.KeyCode != Keys.ControlKey && keyEvent.KeyCode != Keys.ShiftKey && keyEvent.KeyCode != Keys.Menu && keyEvent.KeyCode != Keys.LWin)
|
||||
{
|
||||
if (!empty)
|
||||
{
|
||||
shortcutString += " + ";
|
||||
}
|
||||
shortcutString += keyEvent.KeyCode.ToString();
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(shortcutString))
|
||||
{
|
||||
keyEvent.SuppressKeyPress = true;
|
||||
}
|
||||
|
||||
return shortcutString;
|
||||
}
|
||||
|
||||
public static bool ValidateShortcut(string shortcut)
|
||||
{
|
||||
var valid = string.IsNullOrWhiteSpace(shortcut) || shortcut.Contains("+") || ShortcutIsAllowedWithoutModifier(shortcut);
|
||||
|
||||
if (!valid)
|
||||
{
|
||||
MessageForms.WarningOk("Invalid shortcut. The shortcut should have modifiers and a normal key or be F13-F24.");
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
|
||||
public static bool ShortcutIsAllowedWithoutModifier(string shortcut)
|
||||
{
|
||||
return Enum.TryParse<Keys>(shortcut, out var key) && KeysWithoutModifiers.Contains(key);
|
||||
}
|
||||
|
||||
public static void HandleKeyboardShortcutUp(KeyEventArgs keyEvent)
|
||||
{
|
||||
if (keyEvent.KeyCode == Keys.LWin)
|
||||
{
|
||||
WinKeyDown = false;
|
||||
}
|
||||
}
|
||||
|
||||
public static void InitListView(ListView listView, IEnumerable<string> columns)
|
||||
{
|
||||
foreach (var name in columns)
|
||||
{
|
||||
var columnName = name;
|
||||
var parts = name.Split('|');
|
||||
|
||||
var width = 120;
|
||||
if (parts.Length > 1)
|
||||
{
|
||||
width = int.Parse(parts[1]);
|
||||
columnName = parts[0];
|
||||
}
|
||||
|
||||
var header = listView.Columns.Add(columnName);
|
||||
header.Width = width == 120 ? -2 : width;
|
||||
}
|
||||
}
|
||||
|
||||
public static void AddOrUpdateListItem<T>(ListView listView, List<T> presets, Config config, T preset = null, ListViewItem specItem = null) where T : PresetBase
|
||||
{
|
||||
ListViewItem item = null;
|
||||
if (preset == null)
|
||||
{
|
||||
item = listView.SelectedItems[0];
|
||||
preset = (T)item.Tag;
|
||||
}
|
||||
else
|
||||
{
|
||||
item = specItem;
|
||||
}
|
||||
|
||||
if (preset.id == 0)
|
||||
{
|
||||
preset.id = preset.GetHashCode();
|
||||
}
|
||||
|
||||
var values = preset.GetDisplayValues(config);
|
||||
|
||||
if (item == null)
|
||||
{
|
||||
item = listView.Items.Add(values[0]);
|
||||
item.Tag = preset;
|
||||
for (var i = 1; i < values.Count; i++)
|
||||
{
|
||||
item.SubItems.Add(values[i]);
|
||||
}
|
||||
if (!presets.Any(x => x.id == preset.id))
|
||||
{
|
||||
presets.Add(preset);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
item.Text = values[0];
|
||||
for (var i = 1; i < values.Count; i++)
|
||||
{
|
||||
if (item.SubItems.Count == i)
|
||||
{
|
||||
item.SubItems.Add(values[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
item.SubItems[i].Text = values[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static bool OpenConsole()
|
||||
{
|
||||
if (ConsoleOpened)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!AttachConsole(-1))
|
||||
{
|
||||
AllocConsole();
|
||||
return true;
|
||||
}
|
||||
ConsoleOpened = true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool CloseConsole()
|
||||
{
|
||||
if (!ConsoleOpened)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
SendKeys.SendWait("{ENTER}");
|
||||
var result = FreeConsole();
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Process GetProcessByName(string name, bool skipCurrent = true)
|
||||
{
|
||||
var currentProcessId = Environment.ProcessId;
|
||||
foreach (var process in Process.GetProcesses())
|
||||
{
|
||||
if (process.ProcessName.Equals(name) && (!skipCurrent || process.Id != currentProcessId))
|
||||
{
|
||||
return process;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void StartProcess(string fileName, string arguments = null, bool hidden = false)
|
||||
{
|
||||
Process.Start(new ProcessStartInfo(fileName, arguments) { UseShellExecute = true, WindowStyle = hidden ? ProcessWindowStyle.Hidden : ProcessWindowStyle.Normal });
|
||||
}
|
||||
|
||||
public static string GetResourceFile(string resourceName)
|
||||
{
|
||||
resourceName = "ColorControl.Resources." + resourceName;
|
||||
|
||||
var assembly = Assembly.GetExecutingAssembly();
|
||||
|
||||
using (Stream stream = assembly.GetManifestResourceStream(resourceName))
|
||||
using (StreamReader reader = new StreamReader(stream))
|
||||
{
|
||||
var result = reader.ReadToEnd();
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static bool IsForegroundFullScreenAndDisabledNotifications(Screen screen = null)
|
||||
{
|
||||
return IsNotificationDisabled() && IsForegroundFullScreen(screen);
|
||||
}
|
||||
|
||||
public static bool IsNotificationDisabled()
|
||||
{
|
||||
var result = SHQueryUserNotificationState(out var state);
|
||||
|
||||
if (result == NativeConstants.ERROR_SUCCESS && state != LastNotificationState)
|
||||
{
|
||||
Logger.Debug($"Detected NotificationState change from {LastNotificationState} to {state}");
|
||||
LastNotificationState = state;
|
||||
}
|
||||
|
||||
return NotificationsDisabledStates.Contains(state);
|
||||
//return state != UserNotificationState.QUNS_ACCEPTS_NOTIFICATIONS && state != UserNotificationState.QUNS_QUIET_TIME;
|
||||
}
|
||||
|
||||
public static bool IsForegroundFullScreen(Screen screen = null)
|
||||
{
|
||||
if (screen == null)
|
||||
{
|
||||
screen = Screen.PrimaryScreen;
|
||||
}
|
||||
var hWnd = NativeMethods.GetForegroundWindow();
|
||||
|
||||
NativeMethods.GetWindowRect(hWnd, out var rect);
|
||||
|
||||
/* in case you want the process name:
|
||||
uint procId = 0;
|
||||
GetWindowThreadProcessId(hWnd, out procId);
|
||||
var proc = System.Diagnostics.Process.GetProcessById((int)procId);
|
||||
Console.WriteLine(proc.ProcessName);
|
||||
*/
|
||||
|
||||
return screen.Bounds.Width <= (rect.right - rect.left) && screen.Bounds.Height <= (rect.bottom - rect.top);
|
||||
}
|
||||
|
||||
public static (uint, bool) GetForegroundProcessIdAndIfFullScreen(Screen screen = null)
|
||||
{
|
||||
if (screen == null)
|
||||
{
|
||||
screen = Screen.PrimaryScreen;
|
||||
}
|
||||
var hWnd = NativeMethods.GetForegroundWindow();
|
||||
|
||||
if (hWnd == IntPtr.Zero)
|
||||
{
|
||||
return (0, false);
|
||||
}
|
||||
|
||||
NativeMethods.GetWindowRect(hWnd, out var rect);
|
||||
|
||||
GetWindowThreadProcessId(hWnd, out var processId);
|
||||
|
||||
var isFullScreen = screen.Bounds.Width <= (rect.right - rect.left) && screen.Bounds.Height <= (rect.bottom - rect.top);
|
||||
|
||||
return (processId, isFullScreen);
|
||||
}
|
||||
|
||||
public static Process GetForegroundFullScreenProcess(Screen screen = null)
|
||||
{
|
||||
var (processId, isFullScreen) = GetForegroundProcessIdAndIfFullScreen(screen);
|
||||
|
||||
if (!isFullScreen)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return Process.GetProcessById((int)processId);
|
||||
}
|
||||
|
||||
public static void ParseWords(List<string> target, string text)
|
||||
{
|
||||
target.Clear();
|
||||
|
||||
if (string.IsNullOrEmpty(text))
|
||||
{
|
||||
return;
|
||||
}
|
||||
var words = text.Split(',');
|
||||
for (var i = 0; i < words.Length; i++)
|
||||
{
|
||||
var word = words[i];
|
||||
if (word.IndexOf("(") > -1)
|
||||
{
|
||||
words[i] = word.Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
words[i] = word.Replace(" ", string.Empty);
|
||||
}
|
||||
}
|
||||
target.AddRange(words);
|
||||
}
|
||||
|
||||
public static int ParseInt(string value, int def = 0)
|
||||
{
|
||||
if (int.TryParse(value, out var result))
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
return def;
|
||||
}
|
||||
|
||||
public static int ParseDynamicAsInt(dynamic value, int def = 0)
|
||||
{
|
||||
if (value.Type == JTokenType.Integer)
|
||||
{
|
||||
return (int)value.Value;
|
||||
}
|
||||
if (value.Type == JTokenType.String)
|
||||
{
|
||||
return ParseInt(value.Value, def);
|
||||
}
|
||||
return def;
|
||||
}
|
||||
|
||||
public static async Task<dynamic> GetRestJsonAsync(string url, Action<dynamic> callBack = null)
|
||||
{
|
||||
var httpClient = new HttpClient();
|
||||
httpClient.DefaultRequestHeaders.UserAgent.TryParseAdd("request");
|
||||
|
||||
var response = await httpClient.GetAsync(url);
|
||||
if (response.IsSuccessStatusCode)
|
||||
{
|
||||
var result = await response.Content.ReadAsStringAsync();
|
||||
|
||||
var data = JsonConvert.DeserializeObject<dynamic>(result);
|
||||
|
||||
if (callBack != null)
|
||||
{
|
||||
callBack(data);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
if (callBack != null)
|
||||
{
|
||||
callBack(null);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public class EnumComboBoxItem
|
||||
{
|
||||
public string Name;
|
||||
public int Id;
|
||||
|
||||
public override string ToString()
|
||||
{
|
||||
return Name;
|
||||
}
|
||||
}
|
||||
|
||||
public static class ProcessExtensions
|
||||
{
|
||||
private static string FindIndexedProcessName(int pid, string processName, IEnumerable<Process> processes = null)
|
||||
{
|
||||
var processesByName = processes == null ? Process.GetProcessesByName(processName) : processes.Where(p => p.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase)).ToArray();
|
||||
string processIndexedName = null;
|
||||
|
||||
for (var index = 0; index < processesByName.Length; index++)
|
||||
{
|
||||
processIndexedName = index == 0 ? processName : processName + "#" + index;
|
||||
var processId = new PerformanceCounter("Process", "ID Process", processIndexedName);
|
||||
if ((int)processId.NextValue() == pid)
|
||||
{
|
||||
return processIndexedName;
|
||||
}
|
||||
}
|
||||
|
||||
return processIndexedName;
|
||||
}
|
||||
|
||||
private static Process FindPidFromIndexedProcessName(string indexedProcessName, IEnumerable<Process> processes = null)
|
||||
{
|
||||
var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);
|
||||
var parentProcessId = (int)parentId.NextValue();
|
||||
|
||||
try
|
||||
{
|
||||
return processes == null ? Process.GetProcessById(parentProcessId) : processes.FirstOrDefault(p => p.Id == parentProcessId);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public static Process Parent(this Process process, IEnumerable<Process> processes = null)
|
||||
{
|
||||
var indexedProcessName = FindIndexedProcessName(process.Id, process.ProcessName, processes);
|
||||
if (indexedProcessName == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return FindPidFromIndexedProcessName(indexedProcessName, processes);
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
-60
@@ -1,73 +1,113 @@
|
||||
using NLog;
|
||||
using System;
|
||||
using System.Globalization;
|
||||
using PacketDotNet;
|
||||
using System.Net.NetworkInformation;
|
||||
using SharpPcap;
|
||||
using System.Diagnostics;
|
||||
using SharpPcap.Npcap;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Net.Sockets;
|
||||
|
||||
namespace ColorControl
|
||||
{
|
||||
class WOL
|
||||
{
|
||||
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
|
||||
|
||||
private const string ArgumentExceptionInvalidMacAddressLength = "Invalid MAC address length.";
|
||||
private const string ArgumentExceptionInvalidPasswordLength = "Invalid password length.";
|
||||
private const int DefaultWolPort = 9;
|
||||
|
||||
//You need SharpPcap for this to work
|
||||
|
||||
public static void WakeFunction(string macAddress)
|
||||
public static bool WakeFunction(string macAddress)
|
||||
{
|
||||
/* Retrieve the device list */
|
||||
var devices = CaptureDeviceList.Instance;
|
||||
|
||||
Logger.Debug("Waking device with MAC-address " + macAddress);
|
||||
|
||||
/*If no device exists, print error */
|
||||
if (devices.Count < 1)
|
||||
{
|
||||
Logger.Debug("No network device found on this machine");
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (var device in devices)
|
||||
{
|
||||
//if (device is NpcapDevice npcapDevice)
|
||||
//{
|
||||
// if (!npcapDevice.Interface.GatewayAddresses.Any())
|
||||
// {
|
||||
// continue;
|
||||
// }
|
||||
//}
|
||||
|
||||
Logger.Debug("Opening network device: " + device.Name);
|
||||
|
||||
//Open the device
|
||||
device.Open();
|
||||
|
||||
//A magic packet is a broadcast frame containing anywhere within its payload: 6 bytes of ones
|
||||
//(resulting in hexadecimal FF FF FF FF FF FF), followed by sixteen repetitions
|
||||
|
||||
string response = macAddress.Replace(":", "-");
|
||||
|
||||
var address = PhysicalAddress.Parse("FFFFFFFFFFFF");
|
||||
EthernetPacket ethernet = new EthernetPacket(address, address, EthernetType.WakeOnLan);
|
||||
ethernet.PayloadPacket = new WakeOnLanPacket(PhysicalAddress.Parse(response));
|
||||
|
||||
byte[] bytes = ethernet.Bytes;
|
||||
|
||||
try
|
||||
{
|
||||
//Send the packet out the network device
|
||||
device.SendPacket(bytes);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Debug(e.Message);
|
||||
}
|
||||
|
||||
device.Close();
|
||||
}
|
||||
return WakeFunctionToAllNics(macAddress);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool WakeFunctionToAllNics(string macAddress)
|
||||
{
|
||||
var result = false;
|
||||
|
||||
try
|
||||
{
|
||||
var address = PhysicalAddress.Parse(macAddress);
|
||||
var addressBytes = address.GetAddressBytes();
|
||||
var data = GetWolPacket(addressBytes);
|
||||
|
||||
var interfaces = NetworkInterface.GetAllNetworkInterfaces();
|
||||
|
||||
foreach (var ni in interfaces)
|
||||
{
|
||||
if (ni.NetworkInterfaceType == NetworkInterfaceType.Loopback || ni.Name.Contains("VirtualBox"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Logger.Debug($"Found network: {ni.Name} ({ni.Description}), type: {ni.NetworkInterfaceType}");
|
||||
try
|
||||
{
|
||||
if (/*ni.OperationalStatus == OperationalStatus.Up &&*/ ni.SupportsMulticast && ni.GetIPProperties().GetIPv4Properties() != null)
|
||||
{
|
||||
foreach (var uip in ni.GetIPProperties().UnicastAddresses)
|
||||
{
|
||||
if (uip.Address.ToString().StartsWith("169.254"))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (uip.Address.AddressFamily == AddressFamily.InterNetwork)
|
||||
{
|
||||
Logger.Debug($"Broadcast WOL in network: {ni.Name} ({ni.Description}), local address: {uip.Address}");
|
||||
var local = new IPEndPoint(uip.Address, 0);
|
||||
var udpc = new UdpClient(local);
|
||||
udpc.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
|
||||
udpc.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontRoute, 1);
|
||||
var target = new IPEndPoint(IPAddress.Broadcast, DefaultWolPort);
|
||||
udpc.Send(data, data.Length, target);
|
||||
|
||||
result = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"WakeFunctionToAllNics: while sending to specific network: {ni.Name} ({ni.Description}): {ex.ToLogString()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Logger.Error($"WakeFunctionToAllNics: {ex.ToLogString()}");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <exception cref="ArgumentNullException"><paramref name="macAddress"/> is null.</exception>
|
||||
/// <exception cref="ArgumentException">The length of the <see cref="T:System.Byte" /> array <paramref name="macAddress"/> is not 6.</exception>
|
||||
/// <exception cref="ArgumentException">The length of the <see cref="T:System.Byte" /> array <paramref name="password"/> is not 0 or 6.</exception>
|
||||
private static byte[] GetWolPacket(byte[] macAddress, byte[] password = null)
|
||||
{
|
||||
if (macAddress == null)
|
||||
throw new ArgumentNullException(nameof(macAddress));
|
||||
if (macAddress.Length != 6)
|
||||
throw new ArgumentException(ArgumentExceptionInvalidMacAddressLength);
|
||||
|
||||
password = password ?? new byte[0];
|
||||
if (password.Length != 0 && password.Length != 6)
|
||||
throw new ArgumentException(ArgumentExceptionInvalidPasswordLength);
|
||||
|
||||
var packet = new byte[17 * 6 + password.Length];
|
||||
|
||||
int offset, i;
|
||||
for (offset = 0; offset < 6; ++offset)
|
||||
packet[offset] = 0xFF;
|
||||
|
||||
for (offset = 6; offset < 17 * 6; offset += 6)
|
||||
for (i = 0; i < 6; ++i)
|
||||
packet[i + offset] = macAddress[i];
|
||||
|
||||
if (password.Length > 0)
|
||||
{
|
||||
for (offset = 16 * 6 + 6; offset < (17 * 6 + password.Length); offset += 6)
|
||||
for (i = 0; i < 6; ++i)
|
||||
packet[i + offset] = password[i];
|
||||
}
|
||||
return packet;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,10 +6,12 @@ namespace LgTv
|
||||
public class ClientKeyStore
|
||||
{
|
||||
private string ip;
|
||||
|
||||
public ClientKeyStore(string ip)
|
||||
{
|
||||
this.ip = ip;
|
||||
}
|
||||
|
||||
public string GetClientKey()
|
||||
{
|
||||
var filename = Path.Combine(Utils.GetDataPath(), ip + "_ClientKey.txt");
|
||||
@@ -19,10 +21,34 @@ namespace LgTv
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void SaveClientKey(string key)
|
||||
{
|
||||
var filename = Path.Combine(Utils.GetDataPath(), ip + "_ClientKey.txt");
|
||||
File.WriteAllText(filename, key);
|
||||
}
|
||||
|
||||
public bool HasValidHandShake(string expectedHandShake)
|
||||
{
|
||||
var handShake = GetHandShake();
|
||||
|
||||
return handShake?.Equals(expectedHandShake) ?? false;
|
||||
}
|
||||
|
||||
public string GetHandShake()
|
||||
{
|
||||
var filename = Path.Combine(Utils.GetDataPath(), ip + "_HandShake.txt");
|
||||
if (File.Exists(filename))
|
||||
{
|
||||
return File.ReadAllText(filename);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public void SaveHandShake(string data)
|
||||
{
|
||||
var filename = Path.Combine(Utils.GetDataPath(), ip + "_HandShake.txt");
|
||||
File.WriteAllText(filename, data);
|
||||
}
|
||||
}
|
||||
}
|
||||
+432
-24
@@ -1,13 +1,11 @@
|
||||
using ColorControl;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.ComponentModel;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Windows.Foundation;
|
||||
using Windows.Storage;
|
||||
|
||||
namespace LgTv
|
||||
{
|
||||
@@ -19,9 +17,206 @@ namespace LgTv
|
||||
OK,
|
||||
Exit
|
||||
}
|
||||
|
||||
public enum PictureMode
|
||||
{
|
||||
cinema, eco, expert1, expert2, game, normal, photo, sports, technicolor, vivid, hdrEffect, filmMaker,
|
||||
|
||||
hdrCinema, hdrCinemaBright, hdrExternal, hdrGame, hdrStandard, hdrTechnicolor, hdrVivid, hdrFilmMaker,
|
||||
|
||||
dolbyHdrCinema, dolbyHdrCinemaBright, dolbyHdrDarkAmazon, dolbyHdrGame, dolbyHdrStandard, dolbyHdrVivid, dolbyStandard
|
||||
}
|
||||
|
||||
public enum DynamicRange
|
||||
{
|
||||
sdr, hdr, technicolorHdr, dolbyHdr,
|
||||
sdrALLM, hdrALLM, technicolorHdrALLM, dolbyHdrALLM
|
||||
}
|
||||
|
||||
public enum OffToHigh
|
||||
{
|
||||
off,
|
||||
low,
|
||||
medium,
|
||||
high
|
||||
}
|
||||
|
||||
public enum LowToAuto
|
||||
{
|
||||
low,
|
||||
medium,
|
||||
high,
|
||||
auto
|
||||
}
|
||||
|
||||
public enum OffToOn
|
||||
{
|
||||
off,
|
||||
on
|
||||
}
|
||||
|
||||
public enum OffToAuto2
|
||||
{
|
||||
off,
|
||||
on,
|
||||
auto
|
||||
}
|
||||
|
||||
public enum OffToAuto
|
||||
{
|
||||
off,
|
||||
on,
|
||||
low,
|
||||
medium,
|
||||
high,
|
||||
auto
|
||||
}
|
||||
|
||||
public enum ColorGamut
|
||||
{
|
||||
auto,
|
||||
extended,
|
||||
wide,
|
||||
srgb,
|
||||
native
|
||||
}
|
||||
|
||||
public enum EnergySaving
|
||||
{
|
||||
auto,
|
||||
off,
|
||||
min,
|
||||
med,
|
||||
max,
|
||||
screen_off
|
||||
}
|
||||
|
||||
public enum DynamicTonemapping
|
||||
{
|
||||
on,
|
||||
off,
|
||||
HGIG,
|
||||
}
|
||||
|
||||
public enum TruMotionMode
|
||||
{
|
||||
off,
|
||||
smooth,
|
||||
clear,
|
||||
clearPlus,
|
||||
user
|
||||
}
|
||||
|
||||
public enum WhiteBalanceColorTemperature
|
||||
{
|
||||
cool,
|
||||
medium,
|
||||
warm1,
|
||||
warm2,
|
||||
warm3
|
||||
}
|
||||
|
||||
public enum FalseToTrue
|
||||
{
|
||||
[Description("Disabled")]
|
||||
false_,
|
||||
[Description("Enabled")]
|
||||
true_
|
||||
}
|
||||
|
||||
public enum GammaExp
|
||||
{
|
||||
low,
|
||||
medium,
|
||||
high1,
|
||||
high2
|
||||
}
|
||||
|
||||
public enum HdmiIcon
|
||||
{
|
||||
[Description("HDMI")]
|
||||
hdmigeneric,
|
||||
[Description("Satellite")]
|
||||
satellite,
|
||||
[Description("Set-Top Box")]
|
||||
settopbox,
|
||||
[Description("DVD Player")]
|
||||
dvd,
|
||||
[Description("Blu-ray Player")]
|
||||
bluray,
|
||||
[Description("Home Theater")]
|
||||
hometheater,
|
||||
[Description("Game Console")]
|
||||
gameconsole,
|
||||
[Description("Streaming Box")]
|
||||
streamingbox,
|
||||
[Description("Generic Camera")]
|
||||
camera,
|
||||
[Description("PC")]
|
||||
pc,
|
||||
[Description("Mobile Device")]
|
||||
mobile
|
||||
}
|
||||
|
||||
public enum SoundMode
|
||||
{
|
||||
[Description("AI Sound Pro")]
|
||||
aiSoundPlus,
|
||||
[Description("AI Sound")]
|
||||
aiSound,
|
||||
[Description("Standard")]
|
||||
standard,
|
||||
[Description("Clear Voice")]
|
||||
news,
|
||||
[Description("Music")]
|
||||
music,
|
||||
[Description("Cinema")]
|
||||
movie,
|
||||
[Description("Sports")]
|
||||
sports,
|
||||
[Description("Game Optimizer")]
|
||||
game,
|
||||
[Description("Pagode")]
|
||||
pagode,
|
||||
[Description("Serta Wego")]
|
||||
sertaWego,
|
||||
[Description("Brazilian Punk")]
|
||||
brazilianPunk,
|
||||
[Description("ASC")]
|
||||
asc,
|
||||
[Description("Bass Boost")]
|
||||
bass,
|
||||
}
|
||||
|
||||
public enum SoundOutput
|
||||
{
|
||||
[Description("TV Speaker")]
|
||||
tv_speaker,
|
||||
[Description("HDMI(ARC) Device")]
|
||||
external_arc,
|
||||
[Description("Optical Out Device")]
|
||||
external_optical,
|
||||
[Description("Bluetooth Device")]
|
||||
bt_soundbar,
|
||||
[Description("Mobile Device")]
|
||||
mobile_phone,
|
||||
[Description("Audio Out Device")]
|
||||
lineout,
|
||||
[Description("Wired Headphones")]
|
||||
headphone,
|
||||
[Description("Bluetooth Device + TV Speaker")]
|
||||
tv_speaker_bluetooth,
|
||||
[Description("Optical Out Device + TV Speaker")]
|
||||
tv_external_speaker,
|
||||
[Description("Wired Headphones + TV Speaker")]
|
||||
tv_speaker_headphone,
|
||||
[Description("WiSA Speakers")]
|
||||
wisa_speaker,
|
||||
}
|
||||
|
||||
public class LgTvApi:IDisposable
|
||||
{
|
||||
public bool ConnectionClosed { get => _connection == null || _connection.ConnectionClosed; }
|
||||
public bool ConnectionClosed { get => _connection?.ConnectionClosed ?? true; }
|
||||
|
||||
private readonly LgTvApiCore _connection;
|
||||
private LgWebOsMouseService _mouseConnection;
|
||||
@@ -31,18 +226,7 @@ namespace LgTv
|
||||
private List<Channel> _channelList;
|
||||
private List<App> _appList;
|
||||
private string _ip;
|
||||
|
||||
private const string BEFORE_PAIR_HAND_SHAKE = "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"리모컨 앱\",\"zxx-XX\":\"ЛГ Rэмotэ AПП\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}";
|
||||
|
||||
private const string AFTER_PAIR_HAND_SHAKE = "{\"type\":\"register\",\"id\":\"register_0\",\"payload\":{\"forcePairing\":false,\"pairingType\":\"PROMPT\",\"client-key\":\"CLIENTKEYGOESHERE\",\"manifest\":{\"manifestVersion\":1,\"appVersion\":\"1.1\",\"signed\":{\"created\":\"20140509\",\"appId\":\"com.lge.test\",\"vendorId\":\"com.lge\",\"localizedAppNames\":{\"\":\"LG Remote App\",\"ko-KR\":\"리모컨 앱\",\"zxx-XX\":\"ЛГ Rэмotэ AПП\"},\"localizedVendorNames\":{\"\":\"LG Electronics\"},\"permissions\":[\"TEST_SECURE\",\"CONTROL_INPUT_TEXT\",\"CONTROL_MOUSE_AND_KEYBOARD\",\"READ_INSTALLED_APPS\",\"READ_LGE_SDX\",\"READ_NOTIFICATIONS\",\"SEARCH\",\"WRITE_SETTINGS\",\"WRITE_NOTIFICATION_ALERT\",\"CONTROL_POWER\",\"READ_CURRENT_CHANNEL\",\"READ_RUNNING_APPS\",\"READ_UPDATE_INFO\",\"UPDATE_FROM_REMOTE_APP\",\"READ_LGE_TV_INPUT_EVENTS\",\"READ_TV_CURRENT_TIME\"],\"serial\":\"2f930e2d2cfe083771f68e4fe7bb07\"},\"permissions\":[\"LAUNCH\",\"LAUNCH_WEBAPP\",\"APP_TO_APP\",\"CLOSE\",\"TEST_OPEN\",\"TEST_PROTECTED\",\"CONTROL_AUDIO\",\"CONTROL_DISPLAY\",\"CONTROL_INPUT_JOYSTICK\",\"CONTROL_INPUT_MEDIA_RECORDING\",\"CONTROL_INPUT_MEDIA_PLAYBACK\",\"CONTROL_INPUT_TV\",\"CONTROL_POWER\",\"READ_APP_STATUS\",\"READ_CURRENT_CHANNEL\",\"READ_INPUT_DEVICE_LIST\",\"READ_NETWORK_STATE\",\"READ_RUNNING_APPS\",\"READ_TV_CHANNEL_LIST\",\"WRITE_NOTIFICATION_TOAST\",\"READ_POWER_STATE\",\"READ_COUNTRY_INFO\"],\"signatures\":[{\"signatureVersion\":1,\"signature\":\"eyJhbGdvcml0aG0iOiJSU0EtU0hBMjU2Iiwia2V5SWQiOiJ0ZXN0LXNpZ25pbmctY2VydCIsInNpZ25hdHVyZVZlcnNpb24iOjF9.hrVRgjCwXVvE2OOSpDZ58hR+59aFNwYDyjQgKk3auukd7pcegmE2CzPCa0bJ0ZsRAcKkCTJrWo5iDzNhMBWRyaMOv5zWSrthlf7G128qvIlpMT0YNY+n/FaOHE73uLrS/g7swl3/qH/BGFG2Hu4RlL48eb3lLKqTt2xKHdCs6Cd4RMfJPYnzgvI4BNrFUKsjkcu+WD4OO2A27Pq1n50cMchmcaXadJhGrOqH5YmHdOCj5NSHzJYrsW0HPlpuAx/ECMeIZYDh6RMqaFM2DXzdKX9NmmyqzJ3o/0lkk/N97gfVRLW5hA29yeAwaCViZNCP8iC9aO0q9fQojoa7NQnAtw==\"}]}}}";
|
||||
|
||||
public Task ControlButton(object oK)
|
||||
{
|
||||
// throw new NotImplementedException();
|
||||
return null;
|
||||
}
|
||||
|
||||
private string _currentPariKey;
|
||||
private string _currentPairKey;
|
||||
private string webSocketUri;
|
||||
|
||||
public static async Task<LgTvApi> CreateLgTvApi(string ip, int retries = 1)
|
||||
@@ -78,23 +262,27 @@ namespace LgTv
|
||||
|
||||
public async Task MakeHandShake()
|
||||
{
|
||||
_currentPariKey = _keyStore.GetClientKey();
|
||||
if (_currentPariKey != null)
|
||||
var registerJson = Utils.GetResourceFile("LG_register.json");
|
||||
|
||||
_currentPairKey = _keyStore.GetClientKey();
|
||||
if (_currentPairKey != null && !_currentPairKey.All(k => k == '\0') && _keyStore.HasValidHandShake(registerJson))
|
||||
{
|
||||
var key = AFTER_PAIR_HAND_SHAKE.Replace("CLIENTKEYGOESHERE", _currentPariKey);
|
||||
var key = registerJson.Replace("CLIENTKEYGOESHERE", _currentPairKey);
|
||||
var conn = await _connection.SendCommandAsync(key);
|
||||
_keyStore.SaveClientKey((string)conn.clientKey);
|
||||
return;
|
||||
}
|
||||
|
||||
dynamic result = await _connection.SendCommandAsync(BEFORE_PAIR_HAND_SHAKE);
|
||||
var registerJsonRemovedKey = registerJson.Replace("CLIENTKEYGOESHERE", string.Empty);
|
||||
dynamic result = await _connection.SendCommandAsync(registerJsonRemovedKey);
|
||||
_keyStore.SaveClientKey(result.clientKey);
|
||||
_keyStore.SaveHandShake(registerJson);
|
||||
}
|
||||
|
||||
|
||||
public async Task<bool> Connect()
|
||||
{
|
||||
var ctx = _connection.Connect(new Uri(webSocketUri));
|
||||
var ctx = _connection.Connect(new Uri(webSocketUri));
|
||||
return await ctx;
|
||||
}
|
||||
|
||||
@@ -230,6 +418,17 @@ namespace LgTv
|
||||
{
|
||||
await _connection.SendCommandAsync(new RequestMessage("3d", "ssap://com.webos.service.tv.display/set3DOff"));
|
||||
}
|
||||
|
||||
public async Task TurnScreenOff()
|
||||
{
|
||||
await _connection.SendCommandAsync(new RequestMessage("", "ssap://com.webos.service.tvpower/power/turnOffScreen"));
|
||||
}
|
||||
|
||||
public async Task TurnScreenOn()
|
||||
{
|
||||
await _connection.SendCommandAsync(new RequestMessage("", "ssap://com.webos.service.tvpower/power/turnOnScreen"));
|
||||
}
|
||||
|
||||
public async Task<bool> IsTurnedOn3D()
|
||||
{
|
||||
//Response: { returnValue: true, status3D: { status: true, pattern: ’2Dto3D’ } }
|
||||
@@ -259,7 +458,7 @@ namespace LgTv
|
||||
}
|
||||
public async Task<IEnumerable<ExternalInput>> GetInputList()
|
||||
{
|
||||
var requestMessage = new RequestMessage("input","ssap://tv/getExternalInputList");
|
||||
var requestMessage = new RequestMessage("input","ssap://tv/getExternalInputList");
|
||||
var results = await _connection.SendCommandAsync(requestMessage);
|
||||
var l = new List<ExternalInput>();
|
||||
foreach (var result in results)
|
||||
@@ -278,6 +477,36 @@ namespace LgTv
|
||||
await _connection.SendCommandAsync(requestMessage);
|
||||
}
|
||||
|
||||
public async Task SubscribeVolume(Func<dynamic, bool> callback, dynamic payload = null)
|
||||
{
|
||||
var requestMessage = new RequestMessage("ssap://audio/getVolume", null, "subscribe");
|
||||
|
||||
await _connection.SubscribeAsync(requestMessage, callback);
|
||||
}
|
||||
|
||||
public async Task SubscribePowerState(Func<dynamic, bool> callback, dynamic payload = null)
|
||||
{
|
||||
var requestMessage = new RequestMessage("ssap://com.webos.service.tvpower/power/getPowerState", null, "subscribe");
|
||||
|
||||
await _connection.SubscribeAsync(requestMessage, callback);
|
||||
}
|
||||
|
||||
public async Task SubscribePictureSettings(Func<dynamic, bool> callback, dynamic payload = null)
|
||||
{
|
||||
if (payload == null)
|
||||
{
|
||||
var keys = @"[ ""contrast"", ""backlight"", ""brightness"", ""color"" ]";
|
||||
|
||||
var json = @"{ ""category"": ""picture"", ""keys"": " + keys + @", ""subscribe"": true }";
|
||||
|
||||
payload = JObject.Parse(json);
|
||||
}
|
||||
|
||||
var requestMessage = new RequestMessage("ssap://settings/getSystemSettings", payload, "subscribe");
|
||||
|
||||
await _connection.SubscribeAsync(requestMessage, callback);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<App>> GetLaunchPoints()
|
||||
{
|
||||
_appList = new List<App>();
|
||||
@@ -297,6 +526,15 @@ namespace LgTv
|
||||
return _appList.OrderBy(e => e.Title);
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<string>> GetServiceList()
|
||||
{
|
||||
var list = new List<string>();
|
||||
var requestMessage = new RequestMessage("channels", "ssap://api/getServiceList");
|
||||
var command = _connection.SendCommandAsync(requestMessage);
|
||||
var res = await command;
|
||||
return list;
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<LgApp>> GetApps(bool force = false)
|
||||
{
|
||||
var appList = new List<LgApp>();
|
||||
@@ -327,9 +565,19 @@ namespace LgTv
|
||||
return appList.OrderBy(e => e.title);
|
||||
}
|
||||
|
||||
public async Task<string> LaunchApp(string appId)
|
||||
public async Task<string> LaunchApp(string appId, dynamic @params = null)
|
||||
{
|
||||
var requestMessage = new RequestMessage("ssap://system.launcher/launch", new { id = appId });
|
||||
dynamic payload;
|
||||
if (@params != null)
|
||||
{
|
||||
payload = new { id = appId, @params = @params };
|
||||
}
|
||||
else
|
||||
{
|
||||
payload = new { id = appId };
|
||||
}
|
||||
|
||||
var requestMessage = new RequestMessage("ssap://system.launcher/launch", payload);
|
||||
var response = await _connection.SendCommandAsync(requestMessage);
|
||||
return (string)response.sessionId;
|
||||
}
|
||||
@@ -359,6 +607,166 @@ namespace LgTv
|
||||
return (string)response.sessionId;
|
||||
}
|
||||
|
||||
public async Task SetSystemSettings(string key, object value, string category = "picture")
|
||||
{
|
||||
var jsonValue = ParamToJson(value, ref key);
|
||||
|
||||
var lunauri = "luna://com.webos.settingsservice/setSystemSettings";
|
||||
|
||||
var json = @"{ ""category"": """ + category + @""", ""settings"": { """ + key + @""": " + jsonValue + @" } }";
|
||||
|
||||
var @params = JObject.Parse(json);
|
||||
|
||||
await ExecuteRequest(lunauri, @params);
|
||||
}
|
||||
|
||||
private static string ParamToJson(object value, ref string key)
|
||||
{
|
||||
string jsonValue;
|
||||
var valueType = value.GetType();
|
||||
var intType = typeof(int);
|
||||
if (valueType.IsArray && intType.IsAssignableFrom(valueType.GetElementType()))
|
||||
{
|
||||
var values = ((Array)value).Cast<int>();
|
||||
jsonValue = "[" + string.Join(", ", values.Select(x => x.ToString()).ToArray()) + ']';
|
||||
}
|
||||
else if (key?.Contains("_") == true)
|
||||
{
|
||||
var keys = key.Split('_');
|
||||
key = keys[0];
|
||||
var childKey = keys[1];
|
||||
|
||||
jsonValue = @"{ """ + childKey + @""": " + value + " }";
|
||||
}
|
||||
else if (value is bool)
|
||||
{
|
||||
jsonValue = value.ToString().ToLowerInvariant();
|
||||
}
|
||||
else
|
||||
{
|
||||
jsonValue = $"\"{value}\"";
|
||||
}
|
||||
|
||||
return jsonValue;
|
||||
}
|
||||
|
||||
public async Task SetConfig(string key, object value)
|
||||
{
|
||||
var lunauri = "luna://com.webos.service.config/setConfigs";
|
||||
|
||||
var jsonValue = ParamToJson(value, ref key);
|
||||
|
||||
var @params = JObject.Parse(@"{ ""configs"": { """ + key + @""": " + jsonValue + @" } }");
|
||||
|
||||
await ExecuteRequest(lunauri, @params);
|
||||
}
|
||||
|
||||
public async Task SetDeviceConfig(string id, string icon, string label)
|
||||
{
|
||||
var lunauri = "luna://com.webos.service.eim/setDeviceInfo";
|
||||
|
||||
var iconPng = icon + ".png";
|
||||
|
||||
var @params = new
|
||||
{
|
||||
id = id,
|
||||
label = label,
|
||||
icon = iconPng
|
||||
};
|
||||
|
||||
await ExecuteRequest(lunauri, @params);
|
||||
}
|
||||
|
||||
public async Task Reboot()
|
||||
{
|
||||
//await ExecuteRequest("luna://com.webos.service.oledepl/setGlobalStressReduction", new { enable = true });
|
||||
|
||||
//var requestMessage = new RequestMessage("ssap://com.webos.service.devicereset/requestReboot", new { reason = "broadcastSystemChanged" });
|
||||
//var response = await _connection.SendCommandAsync(requestMessage);
|
||||
|
||||
//await ExecuteRequest("luna://com.webos.settingsservice/setSystemSettings", new { category = "network", settings = new { wolwowlOnOff = "true" } });
|
||||
|
||||
//await ExecuteRequest("luna://com.webos.settingsservice/setSystemSettings", new { category = "general", settings = new { powerOffBySCA3SystemChanged = "true" } });
|
||||
//await ExecuteRequest("luna://com.webos.service.devicereset/requestReboot", new { reason = "broadcastSystemChanged" });
|
||||
}
|
||||
|
||||
private async Task ExecuteRequest(string lunauri, object @params)
|
||||
{
|
||||
var buttons = new[]
|
||||
{
|
||||
new {
|
||||
label = "",
|
||||
onClick = lunauri,
|
||||
@params = @params
|
||||
}
|
||||
};
|
||||
|
||||
var payload = new
|
||||
{
|
||||
message = "Applying...",
|
||||
buttons = buttons,
|
||||
onclose = new { uri = lunauri, @params = @params },
|
||||
onfail = new { uri = lunauri, @params = @params }
|
||||
};
|
||||
|
||||
var requestMessage = new RequestMessage("ssap://system.notifications/createAlert", payload);
|
||||
var response = await _connection.SendCommandAsync(requestMessage);
|
||||
|
||||
var alertId = (string)response.alertId;
|
||||
if (alertId != null)
|
||||
{
|
||||
var closeAlert = new
|
||||
{
|
||||
alertId = alertId
|
||||
};
|
||||
requestMessage = new RequestMessage("ssap://system.notifications/closeAlert", closeAlert);
|
||||
await _connection.SendCommandAsync(requestMessage);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<dynamic> GetSystemInfo(params string[] keys)
|
||||
{
|
||||
var payload = new
|
||||
{
|
||||
keys = keys
|
||||
};
|
||||
|
||||
var requestMessage = new RequestMessage("ssap://system/getSystemInfo", payload);
|
||||
var command = _connection.SendCommandAsync(requestMessage);
|
||||
var res = await command;
|
||||
return res;
|
||||
}
|
||||
|
||||
public async Task<dynamic> GetSystemSettings(string category, params string[] keys)
|
||||
{
|
||||
var payload = new
|
||||
{
|
||||
category = category,
|
||||
keys = keys
|
||||
};
|
||||
|
||||
var requestMessage = new RequestMessage("ssap://settings/getSystemSettings", payload);
|
||||
var command = _connection.SendCommandAsync(requestMessage);
|
||||
var res = await command;
|
||||
return res;
|
||||
}
|
||||
|
||||
public async Task<dynamic> GetSystemSettings2(string category)
|
||||
{
|
||||
var payload = new
|
||||
{
|
||||
category = "dimensionInfo",
|
||||
//dimension = new { input = "default", _3dStatus = "2d", dynamicRange = "sdr" },
|
||||
keys = new[] { "input", "_3dStatus", "colorSystem", "dynamicRange", "gameInput" }
|
||||
};
|
||||
//await ExecuteRequest("luna://com.webos.settingsservice/getSystemSettings", payload);
|
||||
//return null;
|
||||
|
||||
var requestMessage = new RequestMessage("ssap://settings/getSystemSettings", payload);
|
||||
var command = _connection.SendCommandAsync(requestMessage);
|
||||
var res = await command;
|
||||
return res;
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Newtonsoft.Json;
|
||||
using Windows.Networking.Sockets;
|
||||
using Windows.Storage.Streams;
|
||||
using Windows.Web;
|
||||
using Newtonsoft.Json.Serialization;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using Windows.Foundation;
|
||||
using ColorControl;
|
||||
|
||||
namespace LgTv
|
||||
{
|
||||
@@ -31,9 +29,9 @@ namespace LgTv
|
||||
|
||||
public event IsConnectedDelegate IsConnected;
|
||||
private readonly ConcurrentDictionary<string, TaskCompletionSource<dynamic>> _tokens = new ConcurrentDictionary<string, TaskCompletionSource<dynamic>>();
|
||||
private readonly ConcurrentDictionary<string, Func<dynamic, bool>> _callbacks = new ConcurrentDictionary<string, Func<dynamic, bool>>();
|
||||
|
||||
private static void Log(RawRequestMessage message) { }
|
||||
|
||||
private static readonly NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
|
||||
|
||||
public async Task<bool> Connect(Uri uri, bool ignoreReceiver = false)
|
||||
{
|
||||
@@ -47,12 +45,29 @@ namespace LgTv
|
||||
_connection.MessageReceived += Connection_MessageReceived;
|
||||
|
||||
_connection.Closed += Connection_Closed;
|
||||
await _connection.ConnectAsync(uri);
|
||||
using (var cancellationTokenSource = new CancellationTokenSource(5000))
|
||||
{
|
||||
var connectTask = _connection.ConnectAsync(uri).AsTask(cancellationTokenSource.Token);
|
||||
var result = await connectTask.ContinueWith((antecedent) =>
|
||||
{
|
||||
if (antecedent.Status == TaskStatus.RanToCompletion)
|
||||
{
|
||||
// connectTask ran to completion, so we know that the MessageWebSocket is connected.
|
||||
// Add additional code here to use the MessageWebSocket.
|
||||
IsConnected?.Invoke(true);
|
||||
|
||||
IsConnected?.Invoke(true);
|
||||
_messageWriter = new DataWriter(_connection.OutputStream);
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
// connectTask timed out, or faulted.
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
_messageWriter = new DataWriter(_connection.OutputStream);
|
||||
return true;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -67,41 +82,53 @@ namespace LgTv
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public async void SendMessageAsync(string message)
|
||||
public async Task SendMessageAsync(string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
_messageWriter.WriteString(message);
|
||||
await _messageWriter.StoreAsync();
|
||||
|
||||
using (var cancellationTokenSource = new CancellationTokenSource(5000))
|
||||
{
|
||||
await _messageWriter.StoreAsync().AsTask(cancellationTokenSource.Token).ContinueWith((antecedent) =>
|
||||
{
|
||||
if (antecedent.Status != TaskStatus.RanToCompletion)
|
||||
{
|
||||
throw new Exception("SendMessageAsync cancelled due to timeout");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Error("SendMessageAsync: " + e.Message);
|
||||
ConnectionClosed = true;
|
||||
_messageWriter?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
public Task<dynamic> SendCommandAsync(string message)
|
||||
public async Task<dynamic> SendCommandAsync(string message)
|
||||
{
|
||||
var obj = JsonConvert.DeserializeObject<dynamic>(message);
|
||||
return SendCommandAsync((string)obj.id, message);
|
||||
return await SendCommandAsync((string)obj.id, message);
|
||||
}
|
||||
|
||||
private Task<dynamic> SendCommandAsync(string id, string message)
|
||||
private async Task<dynamic> SendCommandAsync(string id, string message)
|
||||
{
|
||||
try
|
||||
{
|
||||
var taskSource = new TaskCompletionSource<dynamic>();
|
||||
_tokens.TryAdd(id, taskSource);
|
||||
SendMessageAsync(message);
|
||||
await SendMessageAsync(message);
|
||||
if (ConnectionClosed)
|
||||
{
|
||||
throw new Exception("Connection closed");
|
||||
}
|
||||
return taskSource.Task;
|
||||
var result = await taskSource.Task.ConfigureAwait(false);
|
||||
|
||||
return result;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -109,7 +136,7 @@ namespace LgTv
|
||||
}
|
||||
}
|
||||
|
||||
public Task<dynamic> SendCommandAsync(RequestMessage message)
|
||||
public async Task<dynamic> SendCommandAsync(RequestMessage message)
|
||||
{
|
||||
var rawMessage = new RawRequestMessage(message, ++_commandCount);
|
||||
var serialized = JsonConvert.SerializeObject(rawMessage, new JsonSerializerSettings()
|
||||
@@ -117,7 +144,21 @@ namespace LgTv
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
});
|
||||
return SendCommandAsync(rawMessage.Id, serialized);
|
||||
return await SendCommandAsync(rawMessage.Id, serialized);
|
||||
}
|
||||
|
||||
public async Task<dynamic> SubscribeAsync(RequestMessage message, Func<dynamic, bool> callback)
|
||||
{
|
||||
var rawMessage = new RawRequestMessage(message, ++_commandCount);
|
||||
var serialized = JsonConvert.SerializeObject(rawMessage, new JsonSerializerSettings()
|
||||
{
|
||||
NullValueHandling = NullValueHandling.Ignore,
|
||||
ContractResolver = new CamelCasePropertyNamesContractResolver()
|
||||
});
|
||||
|
||||
_callbacks.TryAdd(rawMessage.Id, callback);
|
||||
|
||||
return await SendCommandAsync(rawMessage.Id, serialized);
|
||||
}
|
||||
|
||||
private void Connection_Closed(IWebSocket sender, WebSocketClosedEventArgs args)
|
||||
@@ -131,7 +172,17 @@ namespace LgTv
|
||||
{
|
||||
try
|
||||
{
|
||||
using (var dr = args.GetDataReader())
|
||||
var task = new Task<DataReader>(new Func<DataReader>(args.GetDataReader));
|
||||
task.Start();
|
||||
var result = task.Wait(5000);
|
||||
|
||||
var dr = result ? task.Result : null;
|
||||
if (!result)
|
||||
{
|
||||
throw new Exception("Timeout while reading response, possible disconnect");
|
||||
}
|
||||
|
||||
using (dr)
|
||||
{
|
||||
dr.UnicodeEncoding = UnicodeEncoding.Utf8;
|
||||
var message = dr.ReadString(dr.UnconsumedBufferLength);
|
||||
@@ -149,27 +200,68 @@ namespace LgTv
|
||||
}
|
||||
|
||||
}
|
||||
else
|
||||
if (_tokens.TryGetValue(id, out taskCompletion))
|
||||
else if (_tokens.TryGetValue(id, out taskCompletion))
|
||||
{
|
||||
if (id == "register_0") return;
|
||||
if (obj.type == "error")
|
||||
{
|
||||
taskCompletion.SetException(new Exception(obj.error));
|
||||
taskCompletion.SetException(new Exception(obj.error?.ToString()));
|
||||
}
|
||||
//else if (args.Cancelled)
|
||||
//{
|
||||
// taskSource.SetCanceled();
|
||||
//}
|
||||
taskCompletion.TrySetResult(obj.payload);
|
||||
|
||||
if (_callbacks.TryGetValue(id, out Func<dynamic, bool> callback))
|
||||
{
|
||||
try
|
||||
{
|
||||
callback(obj.payload);
|
||||
}
|
||||
catch (Exception callbackException)
|
||||
{
|
||||
Logger.Error($"Connection_MessageReceived: the callback threw an exception: {callbackException.ToLogString()}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
WebErrorStatus status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
|
||||
var status = WebSocketError.GetStatus(ex.GetBaseException().HResult);
|
||||
Logger.Error($"Connection_MessageReceived: status: {status}, exception: {ex.ToLogString()}");
|
||||
|
||||
SetExceptionOnAllTokens(ex);
|
||||
|
||||
ConnectionClosed = true;
|
||||
_messageWriter?.Dispose();
|
||||
}
|
||||
}
|
||||
|
||||
private void SetExceptionOnAllTokens(Exception ex)
|
||||
{
|
||||
//Logger.Debug($"Tokens: {_tokens.Count}");
|
||||
|
||||
foreach (var taskCompletion in _tokens.Values)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (taskCompletion.Task.Status != TaskStatus.RanToCompletion)
|
||||
{
|
||||
Logger.Debug("taskCompletion.Task.Status: " + taskCompletion.Task.Status);
|
||||
taskCompletion.SetException(new Exception(ex.Message));
|
||||
}
|
||||
}
|
||||
catch (Exception ex2)
|
||||
{
|
||||
Logger.Error("SetExceptionOnAllTokens: " + ex2.Message);
|
||||
}
|
||||
}
|
||||
|
||||
_tokens.Clear();
|
||||
}
|
||||
|
||||
public void Close()
|
||||
{
|
||||
_connection?.Close(1, "");
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
using NStandard;
|
||||
using System;
|
||||
using System;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace LgTv
|
||||
@@ -28,7 +27,35 @@ namespace LgTv
|
||||
_8,
|
||||
_9,
|
||||
_0,
|
||||
POWER
|
||||
POWER,
|
||||
VOLUMEUP,
|
||||
VOLUMEDOWN,
|
||||
MUTE,
|
||||
MENU,
|
||||
CC,
|
||||
DASH,
|
||||
CHANNELUP,
|
||||
CHANNELDOWN,
|
||||
LIST,
|
||||
AD,
|
||||
SAP,
|
||||
PROGRAM,
|
||||
PLAY,
|
||||
PAUSE,
|
||||
STOP,
|
||||
REWIND,
|
||||
FASTFORWARD,
|
||||
GUIDE,
|
||||
AMAZON,
|
||||
NETFLIX,
|
||||
MAGNIFIER_ZOOM,
|
||||
LIVE_ZOOM,
|
||||
_3D_MODE,
|
||||
ASPECT_RATIO,
|
||||
RECENT,
|
||||
RECORD,
|
||||
SCREEN_REMOTE,
|
||||
MYAPPS
|
||||
}
|
||||
|
||||
public class LgWebOsMouseService : IDisposable
|
||||
@@ -46,7 +73,7 @@ namespace LgTv
|
||||
}
|
||||
public void SendButton(int number)
|
||||
{
|
||||
_connection.SendMessageAsync($"type:button\nname:{number}\n\n");
|
||||
_connection.SendMessageAsync($"type:button\nname:{number}\n\n").ConfigureAwait(false);
|
||||
}
|
||||
public void SendButton(ButtonType bt)
|
||||
{
|
||||
@@ -55,23 +82,23 @@ namespace LgTv
|
||||
{
|
||||
text = text.Substring(1);
|
||||
}
|
||||
_connection.SendMessageAsync($"type:button\nname:{text}\n\n");
|
||||
_connection.SendMessageAsync($"type:button\nname:{text}\n\n").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
|
||||
public void Move(double dx, double dy, bool drag = false)
|
||||
{
|
||||
_connection.SendMessageAsync($"type:move\ndx:{dx}\ndy:{dy}\ndown:{(drag ? 1 : 0)}\n\n");
|
||||
_connection.SendMessageAsync($"type:move\ndx:{dx}\ndy:{dy}\ndown:{(drag ? 1 : 0)}\n\n").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Scroll(double dx, double dy)
|
||||
{
|
||||
_connection.SendMessageAsync($"type:scroll\ndx:{dx}\ndy:{dy}\n\n");
|
||||
_connection.SendMessageAsync($"type:scroll\ndx:{dx}\ndy:{dy}\n\n").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Click()
|
||||
{
|
||||
_connection.SendMessageAsync("type:click\n\n");
|
||||
_connection.SendMessageAsync("type:click\n\n").ConfigureAwait(false);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
|
||||
@@ -9,10 +9,14 @@ namespace LgTv
|
||||
Prefix = prefix;
|
||||
Uri = uri;
|
||||
}
|
||||
public RequestMessage(string uri,object payload)
|
||||
public RequestMessage(string uri, object payload, string type = "request")
|
||||
{
|
||||
Uri = uri;
|
||||
Payload = JsonConvert.SerializeObject(payload);
|
||||
if (payload != null)
|
||||
{
|
||||
Payload = JsonConvert.SerializeObject(payload);
|
||||
}
|
||||
Type = type;
|
||||
}
|
||||
|
||||
public string Prefix { get; set; }
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Native" version="0.1.0" targetFramework="net472" />
|
||||
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net472" />
|
||||
<package id="NLog" version="4.7.2" targetFramework="net472" />
|
||||
<package id="NStandard" version="0.4.3" targetFramework="net472" />
|
||||
<package id="NvAPIWrapper.Net" version="0.8.0.98" targetFramework="net472" />
|
||||
<package id="NWin32" version="1.0.6" targetFramework="net472" />
|
||||
<package id="PacketDotNet" version="1.0.5" targetFramework="net472" />
|
||||
<package id="SharpPcap" version="5.2.0" targetFramework="net472" />
|
||||
<package id="System.Buffers" version="4.5.1" targetFramework="net472" />
|
||||
<package id="System.Memory" version="4.5.4" targetFramework="net472" />
|
||||
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net472" />
|
||||
<package id="System.Runtime.CompilerServices.Unsafe" version="4.7.0" targetFramework="net472" />
|
||||
<package id="TaskScheduler" version="2.8.20" targetFramework="net472" />
|
||||
</packages>
|
||||
@@ -1,13 +1,55 @@
|
||||
# ColorControl
|
||||
Easily change NVIDIA display settings and/or control LG TV's
|
||||
Easily change NVIDIA and AMD display settings and/or control LG TV's
|
||||
|
||||
If you own a NVIDIA graphics card, this app allows you not to only adjust basic display settings, but some hidden settings as well:
|
||||
## NVIDIA/AMD controller
|
||||
|
||||

|
||||
If you own a NVIDIA or AMD graphics card, this app allows you not to only adjust basic display settings, but some hidden settings as well.
|
||||
For both NVIDIA and AMD graphics cards, you can configure your own presets to change the color depth (6 to 16 bpc), color format (RGB/YUV), refresh rate, dithering and HDR setting. You can assign a global keyboard shortcut to each preset to change the display settings (and HDR!) with just a couple of key presses.
|
||||
The NVIDIA controller even has some more options:
|
||||
* Dynamic range: VESA (Full RGB) or CEA (Limited RGB/YUV)
|
||||
* Color space: to change the color space, but most may not be supported by your tv
|
||||
* Dithering: you can define the dithering mode (Temporal or Spatial) and the dithering bit depth
|
||||
|
||||
And if you own a recent LG TV, you can control your TV through the app (no NVIDIA graphics card needed):
|
||||
Notes:
|
||||
* For a specific setting to be applied, you must include it within the preset. Just click the "Include" menu item and once it is checked, you're good to go.
|
||||
|
||||

|
||||
Screenshot:
|
||||

|
||||
|
||||
## LG controller
|
||||
|
||||
If you own a recent LG TV (2018 or newer, older might work), you can control your TV through the app (no NVIDIA or AMD graphics card needed).
|
||||
At startup of the application it will automatically detect your tv's (see below) if they are on the same network as your pc. If a tv is powered on, it will show a popup by which you can allow ColorControl to send commands to you tv. This will only happen the first time or whenever there's a change in the required permissions. A new version of ColorControl might need this.
|
||||
It is also possible to add a tv manually by using the "Add" button. A name and ip address are required, the MAC address is only necessary for Wake-On-Lan.
|
||||
You can configure as well when to automatically power your tv on or off:
|
||||
* Power on after startup of pc
|
||||
* Power on after resume
|
||||
* Power off on shutdown
|
||||
* Power off on standby
|
||||
* Power off on screensaver and on when screensaver deactivates
|
||||
|
||||
### Presets
|
||||
|
||||
With the presets you can peform actions on your tv you would normally do via the remote control. Properties of a preset:
|
||||
* Name: fill in your own name/description
|
||||
* Device: select the tv to perform the action on. Defaults to "Globally selected device", which is the selected device in the top devices drop down.
|
||||
* App: select the app to launch that is installed on your tv (optional)
|
||||
* Shortcut: enter the global shortcut to execute this preset
|
||||
* Steps: steps to execute sequentially. These steps can be:
|
||||
* Remote control buttons: like RIGHT, LEFT, ENTER, etc.
|
||||
* Actions: directly change picture settings like backlight, contrast, pictureMode, etc. In a dialog you have to specify the value.
|
||||
* NVIDIA/AMD presets: add NVIDIA or AMD presets here that have to execute as well
|
||||
|
||||
Furthermore, you can add a trigger to a preset which means it will execute automatically when a process on your pc is running. See for more information: https://github.com/Maassoft/ColorControl/releases/tag/v4.0.0.0
|
||||
|
||||
Screenshot:
|
||||

|
||||
|
||||
### Auto detecting your tv
|
||||
Check if the TV is listed in Windows Device Manager (Win+X -> Device Manager) under Digital Media Devices. If not then add the TV using Settings (Win+I) -> "Devices" -> "Add Bluetooth or other device" -> "Everything Else", then select your TV by name. It should now appear in Device Manager. (If your TV is not shown when adding devices then your PC is unable to see the TV on the network, check your network settings on both the PC & TV)
|
||||
NOTE: You may have to add the TV as a device more than once before it appears in Device Manager, as Windows can detect the TV as multiple devices.
|
||||
|
||||
WinPcap is no longer used by default, but if you receive WinPcap errors, download and install Npcap (https://nmap.org/npcap/#download) in WinPcap compatibility mode. WinPcap is depreciated under windows 10.
|
||||
|
||||
On the Options-tabpage you can finetune some parameters and/or enable some settings:
|
||||
|
||||
|
||||
Reference in new issue
Block a user