Browse Source

增加工具类

liuyuqi-dellpc 2 years ago
parent
commit
99fdc5b8c2

+ 3 - 2
.gitignore

@@ -1,4 +1,5 @@
-/DayOf1440/bin/Debug
 /DayOf1440/obj
 /.vs/
-/DayOf1440/bin/
+/DayOf1440/bin/
+/PackagingProj/bin
+/PackagingProj/obj

+ 9 - 0
DayOf1440/DayOf1440.csproj

@@ -47,6 +47,7 @@
     <Reference Include="System.Net.Http" />
     <Reference Include="System.Windows.Forms" />
     <Reference Include="System.Xml" />
+    <Reference Include="WindowsBase" />
   </ItemGroup>
   <ItemGroup>
     <Compile Include="MainForm.cs">
@@ -55,6 +56,8 @@
     <Compile Include="MainForm.Designer.cs">
       <DependentUpon>MainForm.cs</DependentUpon>
     </Compile>
+    <Compile Include="NativeMethods\Kernel32.cs" />
+    <Compile Include="NativeMethods\User32.cs" />
     <Compile Include="Program.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
     <Compile Include="Pages\BaseForm.cs">
@@ -66,6 +69,9 @@
     <Compile Include="Pages\LifeForm.Designer.cs">
       <DependentUpon>LifeForm.cs</DependentUpon>
     </Compile>
+    <Compile Include="Utils\HttpUtil.cs" />
+    <Compile Include="Utils\ProcessHelper.cs" />
+    <Compile Include="Utils\SettingHelper.cs" />
     <Compile Include="Utils\SystemSleep.cs" />
     <EmbeddedResource Include="MainForm.resx">
       <DependentUpon>MainForm.cs</DependentUpon>
@@ -136,5 +142,8 @@
     <Content Include="logo.ico" />
     <None Include="Resources\logo.ico" />
   </ItemGroup>
+  <ItemGroup>
+    <Folder Include="DAO\" />
+  </ItemGroup>
   <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
 </Project>

+ 28 - 0
DayOf1440/NativeMethods/Kernel32.cs

@@ -0,0 +1,28 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace DayOf1440.NativeMethods
+{
+
+    public static class Kernel32
+    {
+        [DllImport("kernel32.dll")]
+        public static extern IntPtr LoadLibrary(string lpFileName);
+
+        [DllImport("kernel32.dll")]
+        public static extern int GetCurrentPackageFullName(ref uint packageFullNameLength,
+            [MarshalAs(UnmanagedType.LPWStr)] StringBuilder packageFullName);
+
+        [DllImport("kernel32.dll")]
+        public static extern IntPtr GetCurrentThreadId();
+
+        [DllImport("kernel32.dll")]
+        public static extern bool GetProductInfo(int dwOSMajorVersion, int dwOSMinorVersion, int dwSpMajorVersion,
+            int dwSpMinorVersion, out uint pdwReturnedProductType);
+
+    }
+}

+ 109 - 0
DayOf1440/NativeMethods/User32.cs

@@ -0,0 +1,109 @@
+using System;
+using System.Text;
+using System.Diagnostics.CodeAnalysis;
+using System.Runtime.InteropServices;
+namespace DayOf1440.NativeMethods
+{
+    class User32
+    {
+        #region 限制一个实例
+        [DllImport("User32.dll", EntryPoint = "FindWindow")]
+        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
+
+        [DllImport("User32.dll")]
+        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
+
+        [DllImport("User32.dll")]
+        private static extern bool SetForegroundWindow(IntPtr hWnd);
+
+        #endregion
+
+        public delegate int KeyboardHookProc(int code, int wParam, ref KeyboardHookStruct lParam);
+
+        [DllImport("user32.dll")]
+        public static extern int MoveWindow(IntPtr hWnd, int x, int y, int nWidth, int nHeight,
+            [MarshalAs(UnmanagedType.Bool)] bool bRepaint);
+
+        [DllImport("user32.dll")]
+        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy,
+            uint uFlags);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr SetWindowsHookEx(int idHook, KeyboardHookProc callback, IntPtr hInstance,
+            uint threadId);
+
+        [DllImport("user32.dll")]
+        public static extern bool UnhookWindowsHookEx(IntPtr hInstance);
+
+        [DllImport("user32.dll")]
+        public static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref KeyboardHookStruct lParam);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);
+
+        [DllImport("user32.dll")]
+        public static extern int GetWindowLong(IntPtr hWnd, int nIndex);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr GetForegroundWindow();
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, IntPtr processId);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr GetWindowThreadProcessId(IntPtr hWnd, out uint processId);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr AttachThreadInput(IntPtr idAttach, IntPtr idAttachTo, bool fAttach);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr GetFocus();
+
+        [DllImport("user32.dll", CharSet = CharSet.Auto)]
+        public static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
+
+        [DllImport("user32.dll")]
+        public static extern IntPtr GetParent(IntPtr hWnd);
+
+        [SuppressMessage("ReSharper", "InconsistentNaming")]
+        public struct KeyboardHookStruct
+        {
+            public int vkCode;
+            public int scanCode;
+            public int flags;
+            public int time;
+            public int dwExtraInfo;
+        }
+
+        // ReSharper disable InconsistentNaming
+        public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
+        public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
+        public static readonly IntPtr HWND_TOP = new IntPtr(0);
+        public static readonly IntPtr HWND_BOTTOM = new IntPtr(1);
+
+        public const uint SWP_NOSIZE = 0x0001;
+        public const uint SWP_NOMOVE = 0x0002;
+        public const uint SWP_NOZORDER = 0x0004;
+        public const uint SWP_NOREDRAW = 0x0008;
+        public const uint SWP_NOACTIVATE = 0x0010;
+        public const uint SWP_DRAWFRAME = 0x0020;
+        public const uint SWP_FRAMECHANGED = 0x0020;
+        public const uint SWP_SHOWWINDOW = 0x0040;
+        public const uint SWP_HIDEWINDOW = 0x0080;
+        public const uint SWP_NOCOPYBITS = 0x0100;
+        public const uint SWP_NOOWNERZORDER = 0x0200;
+        public const uint SWP_NOREPOSITION = 0x0200;
+        public const uint SWP_NOSENDCHANGING = 0x0400;
+        public const uint SWP_DEFERERASE = 0x2000;
+        public const uint SWP_ASYNCWINDOWPOS = 0x4000;
+
+        public const int WH_KEYBOARD_LL = 13;
+        public const int WM_KEYDOWN = 0x100;
+        public const int WM_KEYUP = 0x101;
+        public const int WM_SYSKEYDOWN = 0x104;
+        public const int WM_SYSKEYUP = 0x105;
+        public const int GWL_EXSTYLE = -20;
+        public const int WS_EX_NOACTIVATE = 0x08000000;
+        // ReSharper restore InconsistentNaming
+    }
+}

+ 6 - 13
DayOf1440/Program.cs

@@ -1,10 +1,8 @@
-using System;
+using DayOf1440.Utils;
+using System;
 using System.Collections.Generic;
 using System.Diagnostics;
-using System.Linq;
 using System.Reflection;
-using System.Runtime.InteropServices;
-using System.Threading.Tasks;
 using System.Windows.Forms;
 
 namespace DayOf1440
@@ -36,15 +34,6 @@ namespace DayOf1440
             }
         }
 
-        [DllImport("User32.dll", EntryPoint = "FindWindow")]
-        private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
-
-        [DllImport("User32.dll")]
-        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
-
-        [DllImport("User32.dll")]
-        private static extern bool SetForegroundWindow(IntPtr hWnd);
-
         public static Process RunningInstance()
         {
             // 获取当前活动的进程
@@ -66,5 +55,9 @@ namespace DayOf1440
             // 如果没有其他同名进程存在,则返回 null
             return null;
         }
+        /// <summary>
+        /// 是否UWP应用
+        /// </summary>
+        public static readonly bool IsUWP = ProcessHelper.IsRunningAsUWP();
     }
 }

+ 198 - 0
DayOf1440/Utils/HttpUtil.cs

@@ -0,0 +1,198 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Net;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace DayOf1440.Utils
+{
+    class HttpUtil
+    {
+        //public HttpUtil mHttpUtil;
+        HttpWebRequest mHttpWebRequest;
+        private String mHost;
+
+        public HttpUtil(String host)
+        {
+            mHost = host;
+        }
+
+        /// <summary>
+        /// 登录后设置coolie和header
+        /// </summary>
+        /// <param name="abc"></param>
+        /// <returns></returns>
+        public HttpWebRequest SetHeader(List<Dictionary<String, String>> abc)
+        {
+            //WebHeaderCollection
+            //mHttpWebRequest.Headers=abc;
+            return mHttpWebRequest;
+        }
+
+        //public String Get(String apiUrl, List<Directory<string, string>> data, String encoding = "utf-8")
+        //{
+        //    try
+        //    {
+        //        Encoding myEncoding = Encoding.GetEncoding(encoding);
+        //        foreach (Directory<string, string> item in data)
+        //        {
+        //            item.GetHashCode
+        //        }
+        //        string address = apiUrl + "?" + data;
+
+        //        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
+        //        req.Method = "GET";
+        //        using (WebResponse response = req.GetResponse())
+        //        {
+        //            //在这里对接收到的页面内容进行处理  
+        //            StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
+        //            string backdata = reader.ReadToEnd().ToString();
+        //            return backdata;
+        //        }
+        //    }
+        //    catch (Exception ex)
+        //    {
+        //        string error = ex.ToString();
+        //        return "";
+        //    }
+        //}
+
+        public String Get(String apiUrl, String data = "", String encoding = "utf-8")
+        {
+            try
+            {
+                Encoding myEncoding = Encoding.GetEncoding(encoding);
+                string address = apiUrl + "?" + data;
+
+                HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
+                req.Method = "GET";
+                using (WebResponse response = req.GetResponse())
+                {
+                    //在这里对接收到的页面内容进行处理  
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
+                    string backdata = reader.ReadToEnd().ToString();
+                    return backdata;
+                }
+            }
+            catch (Exception ex)
+            {
+                string error = ex.ToString();
+                return "";
+            }
+        }
+
+        /// <summary>
+        /// get请求
+        /// </summary>
+        /// <param name="url"></param>
+        /// <param name="data"></param>
+        /// <param name="encodeing"></param>
+        /// <returns></returns>
+        //public static string Get(string url, string data = "", string encodeing = "utf-8")
+        //{
+        //    try
+        //    {
+        //        Encoding myEncoding = Encoding.GetEncoding(encodeing);
+        //        string address = url + "?" + data;
+
+        //        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(address);
+        //        req.Method = "GET";
+        //        using (WebResponse response = req.GetResponse())
+        //        {
+        //            //在这里对接收到的页面内容进行处理  
+        //            StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
+        //            string backdata = reader.ReadToEnd().ToString();
+        //            return backdata;
+        //        }
+        //    }
+        //    catch (Exception ex)
+        //    {
+        //        string error = ex.ToString();
+        //        return "";
+        //    }
+
+
+        //}
+
+        public static string Post(string url, string data = "", string encodeing = "utf-8")
+        {
+
+            try
+            {
+                Encoding myEncoding = Encoding.GetEncoding(encodeing);
+                string param = data;// Http.UrlEncode(data);
+
+                byte[] postBytes = Encoding.UTF8.GetBytes(param);
+
+                HttpWebRequest req = (HttpWebRequest)
+                HttpWebRequest.Create(url);
+                req.Method = "POST";
+                req.ContentType = "application/x-www-form-urlencoded;charset=utf8";
+                req.ContentLength = postBytes.Length;
+
+                using (Stream reqStream = req.GetRequestStream())
+                {
+                    reqStream.Write(postBytes, 0, postBytes.Length);
+                }
+                using (WebResponse response = req.GetResponse())
+                {
+                    //在这里对接收到的页面内容进行处理  
+                    StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.GetEncoding("utf-8"));
+                    string backdata = reader.ReadToEnd().ToString();
+                    return backdata;
+                }
+            }
+            catch (Exception)
+            {
+                return "";
+            }
+        }
+        /// <summary>
+        /// 下载文件
+        /// </summary>
+        /// <param name="url"></param>
+        public void Download(String url)
+        {
+
+        }
+        /// <summary>
+        /// 上传文件
+        /// </summary>
+        /// <param name="url"></param>
+        public void Upload(String url)
+        {
+
+        }
+        public static string UrlEncode(string str)
+        {
+            StringBuilder sb = new StringBuilder();
+            byte[] byStr = System.Text.Encoding.UTF8.GetBytes(str); //默认是System.Text.Encoding.Default.GetBytes(str)
+            for (int i = 0; i < byStr.Length; i++)
+            {
+                sb.Append(@"%" + Convert.ToString(byStr[i], 16));
+            }
+
+            return (sb.ToString());
+        }
+        public static string UrlDecode(string tmp)
+        {
+            try
+            {
+                string[] tmp1 = tmp.Split(new string[] { "\\u" }, StringSplitOptions.RemoveEmptyEntries);
+                List<char> tmp2 = new List<char>();
+                foreach (string s in tmp1)
+                {
+                    tmp2.Add((char)Convert.ToInt16(s, 16));
+                }
+                string data = (new string(tmp2.ToArray()));
+                return data;
+            }
+            catch (Exception)
+            {
+                return "";
+            }
+        }
+    }
+}

+ 66 - 0
DayOf1440/Utils/ProcessHelper.cs

@@ -0,0 +1,66 @@
+using System;
+using System.Threading.Tasks;
+using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
+using System.IO;
+using DayOf1440.NativeMethods;
+
+namespace DayOf1440.Utils
+{
+    class ProcessHelper
+    {
+
+        private const int ErrorInsufficientBuffer = 0x7A;
+
+        // ReSharper disable once InconsistentNaming
+        public static void PerformAggressiveGC()
+        {
+            // delay some time to make sure that all windows are closed
+            Task.Delay(2000).ContinueWith(t => GC.Collect(GC.MaxGeneration));
+        }
+
+        public static bool IsRunningAsUWP()
+        {
+            try
+            {
+                uint len = 0;
+                var r = Kernel32.GetCurrentPackageFullName(ref len, null);
+
+                return r == ErrorInsufficientBuffer;
+            }
+            catch (EntryPointNotFoundException)
+            {
+                return false;
+            }
+        }
+
+        [SuppressMessage("ReSharper", "InconsistentNaming")]
+        public static bool IsOnWindows10S()
+        {
+            const uint PRODUCT_CLOUD = 0x000000B2; // Windows 10 S
+            const uint PRODUCT_CLOUDN = 0x000000B3; // Windows 10 S N
+
+            Kernel32.GetProductInfo(Environment.OSVersion.Version.Major,
+                Environment.OSVersion.Version.Minor, 0, 0, out var osType);
+
+            return osType == PRODUCT_CLOUD || osType == PRODUCT_CLOUDN;
+        }
+
+        public static void WriteLog(string msg)
+        {
+            Debug.WriteLine(msg);
+
+            var logFilePath = Path.Combine(SettingHelper.LocalDataPath, @"QuickLook.Exception.log");
+
+            using (var writer = new StreamWriter(new FileStream(logFilePath, FileMode.OpenOrCreate,
+                FileAccess.ReadWrite, FileShare.Read)))
+            {
+                writer.BaseStream.Seek(0, SeekOrigin.End);
+
+                writer.WriteLine($"========{DateTime.Now}========");
+                writer.WriteLine(msg);
+                writer.WriteLine();
+            }
+        }
+    }
+}

+ 123 - 0
DayOf1440/Utils/SettingHelper.cs

@@ -0,0 +1,123 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.Serialization;
+using System.Xml;
+namespace DayOf1440.Utils
+{
+    class SettingHelper
+    {
+
+        public static readonly string LocalDataPath =
+             Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"pooi.moe\QuickLook\");
+
+        private static readonly Dictionary<string, XmlDocument> FileCache = new Dictionary<string, XmlDocument>();
+
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        public static T Get<T>(string id, T failsafe = default(T), Assembly calling = null)
+        {
+            if (!typeof(T).IsSerializable && !typeof(ISerializable).IsAssignableFrom(typeof(T)))
+                throw new InvalidOperationException("A serializable Type is required");
+
+            var file = Path.Combine(LocalDataPath,
+                (calling ?? Assembly.GetCallingAssembly()).GetName().Name + ".config");
+
+            var doc = GetConfigFile(file);
+
+            // try to get setting
+            var s = GetSettingFromXml(doc, id, failsafe);
+
+            return s != null ? s : failsafe;
+        }
+
+        [MethodImpl(MethodImplOptions.NoInlining)]
+        public static void Set(string id, object value, Assembly calling = null)
+        {
+            if (!value.GetType().IsSerializable)
+                throw new NotSupportedException("New value if not serializable.");
+
+            var file = Path.Combine(LocalDataPath,
+                (calling ?? Assembly.GetCallingAssembly()).GetName().Name + ".config");
+
+            WriteSettingToXml(GetConfigFile(file), id, value);
+        }
+
+        private static T GetSettingFromXml<T>(XmlDocument doc, string id, T failsafe)
+        {
+            var v = doc.SelectSingleNode($@"/Settings/{id}");
+
+            try
+            {
+                var result = v == null ? failsafe : (T)Convert.ChangeType(v.InnerText, typeof(T));
+                return result;
+            }
+            catch (Exception)
+            {
+                return failsafe;
+            }
+        }
+
+        private static void WriteSettingToXml(XmlDocument doc, string id, object value)
+        {
+            var v = doc.SelectSingleNode($@"/Settings/{id}");
+
+            if (v != null)
+            {
+                v.InnerText = value.ToString();
+            }
+            else
+            {
+                var node = doc.CreateNode(XmlNodeType.Element, id, doc.NamespaceURI);
+                node.InnerText = value.ToString();
+                doc.SelectSingleNode(@"/Settings")?.AppendChild(node);
+            }
+
+            doc.Save(new Uri(doc.BaseURI).LocalPath);
+        }
+
+        private static XmlDocument GetConfigFile(string file)
+        {
+            if (FileCache.ContainsKey(file))
+                return FileCache[file];
+
+            Directory.CreateDirectory(Path.GetDirectoryName(file));
+            if (!File.Exists(file))
+                CreateNewConfig(file);
+
+            var doc = new XmlDocument();
+            try
+            {
+                doc.Load(file);
+            }
+            catch (XmlException)
+            {
+                CreateNewConfig(file);
+                doc.Load(file);
+            }
+
+            if (doc.SelectSingleNode(@"/Settings") == null)
+            {
+                CreateNewConfig(file);
+                doc.Load(file);
+            }
+
+            FileCache.Add(file, doc);
+            return doc;
+        }
+
+        private static void CreateNewConfig(string file)
+        {
+            using (var writer = XmlWriter.Create(file))
+            {
+                writer.WriteStartDocument();
+                writer.WriteStartElement("Settings");
+                writer.WriteEndElement();
+                writer.WriteEndDocument();
+
+                writer.Flush();
+            }
+        }
+    }
+}

+ 5 - 5
PackagingProj/Package.appxmanifest

@@ -7,12 +7,12 @@
   IgnorableNamespaces="uap rescap">
 
   <Identity
-    Name="6db51864-8c5c-47f1-9f43-23fc0774f58a"
+    Name="Zhizhou.DayOf1440"
     Publisher="CN=liuyuqi"
-    Version="1.0.0.0" />
+    Version="1.1.0.0" />
 
   <Properties>
-    <DisplayName>PackagingProj</DisplayName>
+    <DisplayName>DayOf1440</DisplayName>
     <PublisherDisplayName>liuyuqi</PublisherDisplayName>
     <Logo>Images\StoreLogo.png</Logo>
   </Properties>
@@ -31,8 +31,8 @@
       Executable="$targetnametoken$.exe"
       EntryPoint="$targetentrypoint$">
       <uap:VisualElements
-        DisplayName="PackagingProj"
-        Description="PackagingProj"
+        DisplayName="DayOf1440"
+        Description="每一分钟都不平凡"
         BackgroundColor="transparent"
         Square150x150Logo="Images\Square150x150Logo.png"
         Square44x44Logo="Images\Square44x44Logo.png">