├── .gitignore ├── DOCUMENTATION.cs ├── Properties ├── AssemblyInfo.cs ├── Settings.Designer.cs └── Settings.settings ├── Util ├── Pipes │ ├── MessageHandlerPipeServer.cs │ ├── NamedPipeServer.cs │ ├── PipesModuleLoader.cs │ └── pipeclient.ahk ├── x64 │ ├── AutoHotkey.dll │ └── v2_AutoHotkey.dll └── x86 │ ├── AutoHotkey.dll │ └── v2_AutoHotkey.dll ├── _Expressions ├── AHK_Expressions.cs ├── AutoHotkeyExt.cs ├── _ClipboardExt.cs ├── _ControlsExt.cs ├── _ConvertExt.cs ├── _DataGridViewExt.cs ├── _DialogExt.cs ├── _FileFolderExt.cs ├── _ImagesExt.cs ├── _ListsExt.cs ├── _ProcessesExt.cs ├── _StringsExt.cs ├── _TreeViewExt.cs └── _XMLExt.cs ├── _sharpAHK ├── AHK.cs ├── AHK_Expressions.cs ├── AHKcsharp.cs ├── _AutoHotkey.cs ├── _Clipboard.cs ├── _Controls.cs ├── _DateTime.cs ├── _Drive.cs ├── _Encryption.cs ├── _FileFolder.cs ├── _GUI.cs ├── _Hotkeys.cs ├── _INI.cs ├── _Images.cs ├── _Launch.cs ├── _Lists.cs ├── _Math.cs ├── _Monitor.cs ├── _Mouse.cs ├── _Objects.cs ├── _Processes.cs ├── _Registry.cs ├── _Sound.cs ├── _Strings.cs ├── _User32.cs ├── _Variables.cs ├── _Web.cs ├── _WindowManagement.cs ├── _Windows.cs └── _Zip.cs ├── app.config ├── lib ├── AutoHotkey │ ├── AutoHotkey.chm │ └── AutoHotkey.exe └── Util │ ├── AhkEscape.cs │ ├── AutoHotkeyDll.cs │ ├── AutoHotkeyDllLoader.cs │ ├── AutoHotkeyEngine.cs │ ├── EmbededResourceHelper.cs │ ├── Pipes │ ├── MessageHandlerPipeServer.cs │ ├── NamedPipeServer.cs │ ├── PipesModuleLoader.cs │ └── pipeclient.ahk │ ├── ProcessorType.cs │ ├── SafeLibraryHandle.cs │ ├── x64 │ ├── AutoHotkey.dll │ └── v2_AutoHotkey.dll │ └── x86 │ ├── AutoHotkey.dll │ └── v2_AutoHotkey.dll ├── packages.config ├── sharpAHK.csproj ├── sharpAHK.csproj.nuspec ├── sharpAHK.csproj.vspscc ├── sharpAHK.sln └── sharpAHK.sln.nuspec /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.licx 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | 28 | # Visual Studio 2015/2017 cache/options directory 29 | .vs/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # Visual Studio 2017 auto generated files 34 | Generated\ Files/ 35 | 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | 44 | # Build Results of an ATL Project 45 | [Dd]ebugPS/ 46 | [Rr]eleasePS/ 47 | dlldata.c 48 | 49 | # Benchmark Results 50 | BenchmarkDotNet.Artifacts/ 51 | 52 | # .NET Core 53 | project.lock.json 54 | project.fragment.lock.json 55 | artifacts/ 56 | **/Properties/launchSettings.json 57 | 58 | # StyleCop 59 | StyleCopReport.xml 60 | 61 | # Files built by Visual Studio 62 | *_i.c 63 | *_p.c 64 | *_i.h 65 | *.ilk 66 | *.meta 67 | *.obj 68 | *.iobj 69 | *.pch 70 | *.pdb 71 | *.ipdb 72 | *.pgc 73 | *.pgd 74 | *.rsp 75 | *.sbr 76 | *.tlb 77 | *.tli 78 | *.tlh 79 | *.tmp 80 | *.tmp_proj 81 | *.log 82 | *.vspscc 83 | *.vssscc 84 | .builds 85 | *.pidb 86 | *.svclog 87 | *.scc 88 | 89 | # Chutzpah Test files 90 | _Chutzpah* 91 | 92 | # Visual C++ cache files 93 | ipch/ 94 | *.aps 95 | *.ncb 96 | *.opendb 97 | *.opensdf 98 | *.sdf 99 | *.cachefile 100 | *.VC.db 101 | *.VC.VC.opendb 102 | 103 | # Visual Studio profiler 104 | *.psess 105 | *.vsp 106 | *.vspx 107 | *.sap 108 | 109 | # Visual Studio Trace Files 110 | *.e2e 111 | 112 | # TFS 2012 Local Workspace 113 | $tf/ 114 | 115 | */Debug/*.* 116 | *.licx 117 | 118 | # Guidance Automation Toolkit 119 | *.gpState 120 | 121 | # ReSharper is a .NET coding add-in 122 | _ReSharper*/ 123 | *.[Rr]e[Ss]harper 124 | *.DotSettings.user 125 | 126 | # JustCode is a .NET coding add-in 127 | .JustCode 128 | 129 | # TeamCity is a build add-in 130 | _TeamCity* 131 | 132 | # DotCover is a Code Coverage Tool 133 | *.dotCover 134 | 135 | # AxoCover is a Code Coverage Tool 136 | .axoCover/* 137 | !.axoCover/settings.json 138 | 139 | # Visual Studio code coverage results 140 | *.coverage 141 | *.coveragexml 142 | 143 | # NCrunch 144 | _NCrunch_* 145 | .*crunch*.local.xml 146 | nCrunchTemp_* 147 | 148 | # MightyMoose 149 | *.mm.* 150 | AutoTest.Net/ 151 | 152 | # Web workbench (sass) 153 | .sass-cache/ 154 | 155 | # Installshield output folder 156 | [Ee]xpress/ 157 | 158 | # DocProject is a documentation generator add-in 159 | DocProject/buildhelp/ 160 | DocProject/Help/*.HxT 161 | DocProject/Help/*.HxC 162 | DocProject/Help/*.hhc 163 | DocProject/Help/*.hhk 164 | DocProject/Help/*.hhp 165 | DocProject/Help/Html2 166 | DocProject/Help/html 167 | 168 | # Click-Once directory 169 | publish/ 170 | 171 | # Publish Web Output 172 | *.[Pp]ublish.xml 173 | *.azurePubxml 174 | # Note: Comment the next line if you want to checkin your web deploy settings, 175 | # but database connection strings (with potential passwords) will be unencrypted 176 | *.pubxml 177 | *.publishproj 178 | 179 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 180 | # checkin your Azure Web App publish settings, but sensitive information contained 181 | # in these scripts will be unencrypted 182 | PublishScripts/ 183 | 184 | # NuGet Packages 185 | *.nupkg 186 | # The packages folder can be ignored because of Package Restore 187 | **/[Pp]ackages/* 188 | # except build/, which is used as an MSBuild target. 189 | !**/[Pp]ackages/build/ 190 | # Uncomment if necessary however generally it will be regenerated when needed 191 | #!**/[Pp]ackages/repositories.config 192 | # NuGet v3's project.json files produces more ignorable files 193 | *.nuget.props 194 | *.nuget.targets 195 | 196 | # Microsoft Azure Build Output 197 | csx/ 198 | *.build.csdef 199 | 200 | # Microsoft Azure Emulator 201 | ecf/ 202 | rcf/ 203 | 204 | # Windows Store app package directories and files 205 | AppPackages/ 206 | BundleArtifacts/ 207 | Package.StoreAssociation.xml 208 | _pkginfo.txt 209 | *.appx 210 | 211 | # Visual Studio cache files 212 | # files ending in .cache can be ignored 213 | *.[Cc]ache 214 | # but keep track of directories ending in .cache 215 | !*.[Cc]ache/ 216 | 217 | # Others 218 | ClientBin/ 219 | ~$* 220 | *~ 221 | *.dbmdl 222 | *.dbproj.schemaview 223 | *.jfm 224 | *.pfx 225 | *.publishsettings 226 | orleans.codegen.cs 227 | 228 | # Including strong name files can present a security risk 229 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 230 | #*.snk 231 | 232 | # Since there are multiple workflows, uncomment next line to ignore bower_components 233 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 234 | #bower_components/ 235 | 236 | # RIA/Silverlight projects 237 | Generated_Code/ 238 | 239 | # Backup & report files from converting an old project file 240 | # to a newer Visual Studio version. Backup files are not needed, 241 | # because we have git ;-) 242 | _UpgradeReport_Files/ 243 | Backup*/ 244 | UpgradeLog*.XML 245 | UpgradeLog*.htm 246 | ServiceFabricBackup/ 247 | *.rptproj.bak 248 | 249 | # SQL Server files 250 | *.mdf 251 | *.ldf 252 | *.ndf 253 | 254 | # Business Intelligence projects 255 | *.rdl.data 256 | *.bim.layout 257 | *.bim_*.settings 258 | *.rptproj.rsuser 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush 299 | .cr/ 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | -------------------------------------------------------------------------------- /DOCUMENTATION.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoHotkey.Interop 8 | { 9 | class DOCUMENTATION 10 | { 11 | // Related Sites: 12 | // 13 | // Stories Promoting Use of AHK 14 | // https://lifehacker.com/search?blogId=17&q=Autohotkey×tamp=1568161650090 15 | 16 | 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("sharpAHK")] 9 | [assembly: AssemblyDescription("AutoHotkey Interop/Wrapper/Expanded Library")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("LITM")] 12 | [assembly: AssemblyProduct("sharpAHK")] 13 | [assembly: AssemblyCopyright("Copyright LucidMethod 2018-3000")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("8a7cbbfe-ccb2-42ef-b90f-d937ae6ed741")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | [assembly: AssemblyVersion("1.2.7.7")] 35 | [assembly: AssemblyFileVersion("1.2.7.7")] 36 | 37 | [assembly: InternalsVisibleTo("AutoHotkey.Interop.Tests")] 38 | -------------------------------------------------------------------------------- /Properties/Settings.Designer.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace AutoHotkey.Interop.Properties { 12 | 13 | 14 | [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] 15 | [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")] 16 | internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { 17 | 18 | private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); 19 | 20 | public static Settings Default { 21 | get { 22 | return defaultInstance; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Properties/Settings.settings: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /Util/Pipes/MessageHandlerPipeServer.cs: -------------------------------------------------------------------------------- 1 | //using System; 2 | //using System.Collections.Generic; 3 | //using System.Linq; 4 | //using System.Text; 5 | //using System.Threading.Tasks; 6 | 7 | //namespace AutoHotkey.Interop.Pipes 8 | //{ 9 | // internal class MessageHandlerPipeServer : NamedPipeServer 10 | // { 11 | // Func messageHandler = null; 12 | 13 | // public MessageHandlerPipeServer(string pipeName, Func messageHandler) : base(pipeName) { 14 | // if (pipeName == null) throw new ArgumentNullException("pipeName"); 15 | // if (messageHandler == null) throw new ArgumentNullException("messageHandler"); 16 | 17 | // this.messageHandler = messageHandler; 18 | // } 19 | 20 | // protected override string HandleClientMessage(string clientMessage) { 21 | // return messageHandler(clientMessage); 22 | // } 23 | // } 24 | //} 25 | -------------------------------------------------------------------------------- /Util/Pipes/NamedPipeServer.cs: -------------------------------------------------------------------------------- 1 | //using System; 2 | //using System.Collections.Generic; 3 | //using System.IO; 4 | //using System.IO.Pipes; 5 | //using System.Linq; 6 | //using System.Text; 7 | //using System.Threading.Tasks; 8 | 9 | //namespace AutoHotkey.Interop.Pipes 10 | //{ 11 | // internal abstract class NamedPipeServer 12 | // { 13 | // private readonly string pipeName; 14 | // private volatile NamedPipeServerStream serverStream; 15 | 16 | // public bool IsClientConnected { 17 | // get { 18 | // if (serverStream == null) 19 | // return false; 20 | // else 21 | // return serverStream.IsConnected; 22 | // } 23 | // } 24 | 25 | // public NamedPipeServer(string pipeName) { 26 | // this.pipeName = pipeName; 27 | // } 28 | 29 | // public void Start() { 30 | // serverStream = MakeNamedPipeServerStream(pipeName); 31 | // serverStream.BeginWaitForConnection(DoConnectionLoop, null); 32 | // } 33 | 34 | // private async void DoConnectionLoop(IAsyncResult result) { 35 | // if (!result.IsCompleted) return; 36 | // if (serverStream == null) return; 37 | 38 | // //IOException = pipe is broken 39 | // //ObjectDisposedException = cannot access closed pipe 40 | // //OperationCanceledException - read was canceled 41 | 42 | // //ACCEPT CLIENT CONNECTION 43 | // try { 44 | // serverStream.EndWaitForConnection(result); 45 | // } 46 | // catch (IOException) { RebuildNamedPipe(); return; } 47 | // catch (ObjectDisposedException) { RebuildNamedPipe(); return; } 48 | // catch (OperationCanceledException) { RebuildNamedPipe(); return; } 49 | 50 | // while (IsClientConnected) { 51 | // string clientMessage = null; 52 | // string serverResponce = null; 53 | 54 | // // READ FROM CLIENT 55 | // if (serverStream == null) break; 56 | // try { 57 | // clientMessage = await ReadClientMessage(serverStream); 58 | // } 59 | // catch (IOException) { RebuildNamedPipe(); return; } 60 | // catch (ObjectDisposedException) { RebuildNamedPipe(); return; } 61 | // catch (OperationCanceledException) { RebuildNamedPipe(); return; } 62 | 63 | // //PROCESS CLIENT MESSAGE 64 | // serverResponce = HandleClientMessage(clientMessage); 65 | 66 | 67 | 68 | // //SEND RESPONCE BACK TO CLIENT 69 | // if (serverStream == null) break; 70 | // try { 71 | // await SendResponceToClient(serverStream, serverResponce); 72 | // } 73 | // catch (IOException) { RebuildNamedPipe(); return; } 74 | // catch (ObjectDisposedException) { RebuildNamedPipe(); return; } 75 | // catch (OperationCanceledException) { RebuildNamedPipe(); return; } 76 | // } 77 | 78 | // //client disconnected, relisten 79 | // if (serverStream != null) 80 | // serverStream.BeginWaitForConnection(DoConnectionLoop, null); 81 | // } 82 | 83 | // private void RebuildNamedPipe() { 84 | // this.Shutdown(); 85 | // serverStream = MakeNamedPipeServerStream(pipeName); 86 | // serverStream.BeginWaitForConnection(DoConnectionLoop, null); 87 | // } 88 | 89 | // protected abstract string HandleClientMessage(string clientMessage); 90 | 91 | // private static async Task SendResponceToClient(NamedPipeServerStream stream, string serverResponce) { 92 | // byte[] responceData = Encoding.Unicode.GetBytes(serverResponce); 93 | // await stream.WriteAsync(responceData, 0, responceData.Length); 94 | // await stream.FlushAsync(); 95 | // stream.WaitForPipeDrain(); 96 | // } 97 | 98 | // private static async Task ReadClientMessage(NamedPipeServerStream stream) { 99 | // byte[] buffer = new byte[65535]; 100 | // int read = await stream.ReadAsync(buffer, 0, buffer.Length); 101 | // string clientString = Encoding.Unicode.GetString(buffer, 0, read); 102 | // return clientString; 103 | // } 104 | 105 | // public void Shutdown() { 106 | // if (serverStream != null) { 107 | // try { serverStream.Close(); } catch { } 108 | // try { serverStream.Dispose(); } catch { } 109 | // serverStream = null; 110 | // } 111 | // } 112 | 113 | 114 | // private NamedPipeServerStream MakeNamedPipeServerStream(string pipeName) { 115 | // return new System.IO.Pipes.NamedPipeServerStream(pipeName, 116 | // System.IO.Pipes.PipeDirection.InOut, 117 | // System.IO.Pipes.NamedPipeServerStream.MaxAllowedServerInstances, 118 | // System.IO.Pipes.PipeTransmissionMode.Byte, 119 | // System.IO.Pipes.PipeOptions.Asynchronous); 120 | // } 121 | // } 122 | //} 123 | -------------------------------------------------------------------------------- /Util/Pipes/PipesModuleLoader.cs: -------------------------------------------------------------------------------- 1 | //using System; 2 | //using System.Collections.Generic; 3 | //using System.Linq; 4 | //using System.Text; 5 | //using System.Threading.Tasks; 6 | 7 | //namespace AutoHotkey.Interop.Pipes 8 | //{ 9 | // public static class PipesModuleLoader 10 | // { 11 | // public static object lockObj = new object(); 12 | // internal static MessageHandlerPipeServer Server { get; private set; } 13 | 14 | // public static void LoadPipesModule(Func messageHandler) { 15 | // lock (lockObj) { 16 | // var pipename = GeneratePipeName(); 17 | // InitPipeServer(pipename, messageHandler); 18 | // InitPipeClient(pipename); 19 | // } 20 | // } 21 | 22 | // private static void InitPipeClient(string pipename) { 23 | // //only load pipe client once, by checking for pipeclient_getversion function 24 | // if (!AutoHotkeyEngine.Instance.FunctionExists("pipeclient_getversion")) { 25 | // var ahk_pipeclient_lib = Util.EmbededResourceHelper.ExtractToText(typeof(PipesModuleLoader).Assembly, "Pipes/pipeclient.ahk"); 26 | // AutoHotkeyEngine.Instance.LoadScript(ahk_pipeclient_lib); 27 | // } 28 | // else { 29 | // AutoHotkeyEngine.Instance.LoadScript("A__PIPECLIENT.close()"); 30 | // } 31 | 32 | // AutoHotkeyEngine.Instance.LoadScript(string.Format( 33 | // "A__PIPECLIENT := new pipeclient({0})", 34 | // AhkEscape.Quote(pipename))); 35 | // } 36 | 37 | // private static void InitPipeServer(string pipename, Func messageHandler) { 38 | // if (Server != null) { 39 | // Server.Shutdown(); 40 | // } 41 | 42 | // Server = new MessageHandlerPipeServer(pipename, messageHandler); 43 | // Server.Start(); 44 | // } 45 | 46 | // private static string GeneratePipeName() { 47 | // return "AHK-PIPE-" + Guid.NewGuid().ToString().Replace("-", ""); 48 | // } 49 | // } 50 | //} 51 | -------------------------------------------------------------------------------- /Util/Pipes/pipeclient.ahk: -------------------------------------------------------------------------------- 1 | __showvar(msg, var) { 2 | msgbox % msg . " =`r`n`r`n" . var 3 | } 4 | 5 | __showlasterror() { 6 | __showvar("last error", A_LastError) 7 | } 8 | 9 | 10 | SendPipeMessage(strMessage) { 11 | global A__PIPECLIENT 12 | A__PIPECLIENT.write(strMessage) 13 | sleep, 100 14 | A__PIPECLIENT_RESULT := A__PIPECLIENT.read() 15 | sleep, 100 16 | return A__PIPECLIENT_RESULT 17 | } 18 | 19 | ; get version - also required to make sure pipe client is not loaded twice 20 | pipeclient_getversion() { 21 | return "v1.0" 22 | } 23 | 24 | pipeclient_log(strMessage) { 25 | 26 | } 27 | 28 | class WinApiErrorCodes { 29 | static ERROR_PIPE_NOT_CONNECTED := 233 30 | static ERROR_INVALID_HANDLE := 6 31 | static ERROR_PIPE_BUSY := 231 32 | static ERROR_NOACCESS := 998 33 | } 34 | 35 | class pipeclient { 36 | pipe_name := "" 37 | pipe_handle := "" 38 | 39 | 40 | __New(name) { 41 | this.pipe_name := this.__get_full_pipe_name(name) 42 | this.pipe_handle := this.__get_pipe_handle(this.pipe_name) 43 | } 44 | 45 | 46 | is_connected() { 47 | b := this.get_bytes_to_read() ; call the peeknamedpipe, in order to check last error 48 | return A_LastError == 0 ; this will be something like '233' if there was an error 49 | } 50 | 51 | 52 | get_bytes_to_read() { 53 | buffer_size := 2 54 | buffer := "" 55 | VarSetCapacity(buffer, buffer_size) 56 | 57 | bytes_read := 0 58 | total_bytes_available := 0 59 | bytes_left_in_message := 0 60 | 61 | ret := DllCall("PeekNamedPipe" 62 | ,"Ptr", this.pipe_handle 63 | ,"Ptr", &buffer 64 | ,"Uint*", buffer_size 65 | ,"Uint*", bytes_read 66 | ,"Uint*", total_bytes_available 67 | ,"Uint*", bytes_left_in_message) 68 | 69 | 70 | if (ret == 0) ; no data to read 71 | { 72 | ; MsgBox, problem peeking 73 | ; showlasterror() 74 | return -1 75 | } 76 | else 77 | { 78 | return total_bytes_available 79 | } 80 | } 81 | 82 | 83 | wait_for_data_to_read(max_wait_time := 0) { 84 | waited := 0 85 | step := 100 86 | 87 | buffer_size := this.get_bytes_to_read() 88 | 89 | while (buffer_size <= 0) { 90 | Sleep, %step% 91 | waited := waited + step 92 | 93 | if (max_wait_time > 0 && waited >= max_wait_time) 94 | return False 95 | 96 | buffer_size := this.get_bytes_to_read() 97 | } 98 | 99 | return True 100 | } 101 | 102 | read() { 103 | wait_result := this.wait_for_data_to_read() ;wait infintely for data 104 | ;showvar("read - wait result", wait_result) 105 | 106 | buffer_size := this.get_bytes_to_read() 107 | ;showvar("read - buffer_size", buffer_size) 108 | 109 | buffer := "" 110 | VarSetCapacity(buffer, buffer_size) 111 | 112 | ret := DllCall("ReadFile" 113 | ,"Ptr", this.pipe_handle 114 | ,"Str", buffer 115 | ,"UInt", buffer_size 116 | ,"UInt*", bytes_read 117 | ,"UInt", 0) 118 | 119 | ; Trim results data down to only the bytes read 120 | ; use memcpy to do this 121 | if (ret == 1) ; if read was successful 122 | { 123 | result := "" 124 | VarSetCapacity(result, bytes_read) 125 | DllCall("msvcrt\memcpy", "str", result, "ptr", &buffer, "ptr", bytes_read) 126 | ;showvar("read - results", result) 127 | return result 128 | } 129 | else { ;read failed due to error 130 | return 131 | } 132 | } 133 | 134 | write(msg) { 135 | ;add in BOM 136 | ;msg := (A_IsUnicode ? chr(0xfeff) : chr(239) chr(187) chr(191)) . msg 137 | 138 | buffer := msg 139 | buffer_length := (A_IsUnicode ? StrLen(buffer) * 2 : StrLen(buffer)) 140 | num_of_bytes_written := 0 141 | 142 | DllCall("WriteFile" 143 | ,"Ptr", this.pipe_handle 144 | ,"Str", buffer 145 | ,"UInt", buffer_length 146 | ,"UInt*", bytes_written 147 | ,"UInt", 0) 148 | 149 | return bytes_written 150 | } 151 | 152 | close() { 153 | DllCall("CloseHandle", "Ptr", this.pipe_handle) 154 | } 155 | 156 | 157 | __get_full_pipe_name(name) { 158 | if (RegExMatch(name, "^\\\\.\\pipe\\")) 159 | return name 160 | else 161 | return "\\.\pipe\" . name 162 | } 163 | 164 | __get_pipe_handle(name) { 165 | GENERIC_WRITE := 0x40000000 166 | GENERIC_READ := 0x80000000 167 | access := GENERIC_READ | GENERIC_WRITE 168 | 169 | return DllCall("CreateFile" 170 | ,"Str" , name 171 | ,"UInt", access 172 | ,"UInt", 3 ; share read / write 173 | ,"UInt", 0 174 | ,"UInt", 3 ; open existing file 175 | ,"UInt", 0 176 | ,"UInt", 0) 177 | } 178 | } 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /Util/x64/AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/Util/x64/AutoHotkey.dll -------------------------------------------------------------------------------- /Util/x64/v2_AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/Util/x64/v2_AutoHotkey.dll -------------------------------------------------------------------------------- /Util/x86/AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/Util/x86/AutoHotkey.dll -------------------------------------------------------------------------------- /Util/x86/v2_AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/Util/x86/v2_AutoHotkey.dll -------------------------------------------------------------------------------- /_Expressions/AHK_Expressions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using AutoHotkey.Interop.Util; 7 | using System.Windows.Forms; 8 | using System.IO; 9 | using System.Threading; 10 | using System.Text.RegularExpressions; 11 | using System.Drawing; 12 | using System.Reflection; 13 | using System.Data; 14 | using System.Diagnostics; 15 | using System.IO.Compression; 16 | using System.Security.Cryptography; 17 | using System.Runtime.InteropServices; 18 | using Microsoft.VisualBasic.FileIO; 19 | using Microsoft.VisualBasic.Devices; 20 | using System.Net; 21 | using AHKExpressions; 22 | using sharpAHK; 23 | //using ScintillaNET; 24 | using System.Drawing.Imaging; 25 | using System.Xml.Serialization; 26 | using System.Timers; 27 | using System.Configuration; 28 | using System.Data.SqlClient; 29 | using System.Web; 30 | using System.Xml; 31 | using static sharpAHK._AHK; 32 | 33 | namespace AHKExpressions 34 | { 35 | 36 | /// 37 | /// SharpAHK Text / Control / Object Extension Class 38 | /// 39 | public static partial class StringExtension 40 | { 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /_Expressions/AutoHotkeyExt.cs: -------------------------------------------------------------------------------- 1 | using sharpAHK; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace AHKExpressions 9 | { 10 | public static partial class AHKExpressions 11 | { 12 | // #region === AHK_DLL === 13 | 14 | #region === Log / Debug === 15 | 16 | ///// 17 | ///// Error Level Message / Last Executed Commands / Debug Functions 18 | ///// 19 | //public static void debug(bool DebugDisplay = false) 20 | //{ 21 | // bool ErrorLevel = ahkGlobal.ErrorLevel; // true if error level detected in ahk command 22 | // bool ErrorLevelEnabled = ahkGlobal.ErrorLevelEnabled; // true if error level information is available for this command 23 | // string ErrorLevelValue = ahkGlobal.ErrorLevelValue; // ErrorLevel variable value returned from AHK session 24 | // string ErrorLevelMsg = ahkGlobal.ErrorLevelMsg; // assembled error level message to display 25 | // string ErrorLevelCustom = ahkGlobal.ErrorLevelCustom; // custom error level text for a command 26 | 27 | 28 | // string LastOutputVarName = ahkGlobal.LastOutputVarName; 29 | // string LastOutputVarValue = ahkGlobal.LastOutputVarValue; 30 | 31 | // string lastCShpar = ahkGlobal.cSharpCmd; 32 | // string LastLine = ahkGlobal.LastLine; 33 | // string LastAction = ahkGlobal.LastAction; 34 | 35 | // string sessionInfo = ahkSessionInfo(false); 36 | 37 | // string errorLogH = errorLogHist(true); 38 | // string cmdH = cmdHist(true); 39 | 40 | // if (DebugDisplay) 41 | // MessageBox.Show("LastFunction = " + lastCShpar + "\nLastAction= " + LastAction + "\nErrorLevel= " + ErrorLevel.ToString() + "\nErrorMsg= " + ErrorLevelMsg + "\nValue= " + ErrorLevelValue + "\n\nLastLine= " + LastLine); 42 | //} 43 | 44 | //public static void Log(object entry) // not setup 45 | //{ 46 | // _AHK ahk = new _AHK(); 47 | // ahk.Log(entry); 48 | //} 49 | 50 | // Log / Hist Display|Return 51 | 52 | public static string cmdHist(bool Display = false) // sharpAHK command history 53 | { 54 | _AHK ahk = new _AHK(); 55 | return ahk.cmdHist(Display); 56 | } 57 | 58 | public static string errorLogHist(bool Display = false) 59 | { 60 | _AHK ahk = new _AHK(); 61 | return ahk.errorLogHist(Display); 62 | } 63 | 64 | public static string loadedAHKList(bool Display = false) // displays list of loaded ahk file in current session 65 | { 66 | _AHK ahk = new _AHK(); 67 | return ahk.loadedAHKList(Display); 68 | } 69 | 70 | #endregion 71 | 72 | 73 | // AHK Session 74 | 75 | /// Resets Global AHK Session - Causes next AHK call to create a new AHK session. Resets all Hotkeys/Functions/Variables in Memory 76 | public static void New_AHKSession(bool NewInstance = false) 77 | { 78 | _AHK ahk = new _AHK(); 79 | ahk.New_AHKSession(NewInstance); 80 | } 81 | 82 | /// Executes AHK Command, Returns Variable Value if ReturnVar is Populated 83 | /// AHK Line / Collection of AHK Commands 84 | /// Variable name to return value of from AHK Session after executing ahkSTRING 85 | /// Option To Initiate New AHK Instance - Resets Previously Used Variables and Loaded AHK 86 | /// Returns String with Value of ReturnVar if Provided 87 | public static string Execute(string ahkSTRING, string ReturnVar = "OutputVar", bool NewSession = false) 88 | { 89 | _AHK ahk = new _AHK(); 90 | return ahk.Execute(ahkSTRING, ReturnVar, NewSession); 91 | } 92 | 93 | /// Return the Contents of an AHK Variable Name 94 | /// Name of the Variable To Return from AHK 95 | public static string GetVar(string VarName = "OutputVar") 96 | { 97 | _AHK ahk = new _AHK(); 98 | return ahk.GetVar(VarName); 99 | } 100 | 101 | /// Programmatically set variable value in AHK Session 102 | /// Variable Name in AHK Session 103 | /// Value to Assign Variable Name 104 | public static void SetVar(string VarName, string VarValue = "") 105 | { 106 | _AHK ahk = new _AHK(); 107 | ahk.SetVar(VarName, VarValue); 108 | } 109 | 110 | /// Load AHK Script from a .AHK File Into Current or New AHK Session 111 | /// AHK Code or FilePath as a String to Load in Current or New AHK Instance 112 | /// Option to Reset AHK Instance, Clearing Previously Saved Hotkeys and Variable Values in Memory 113 | /// Option to add Return in front of code added. Keeps from executing your script while loading. 114 | /// False if File Not Found - True if File Found. (Does not indicate success in loading ahk functionality) 115 | public static bool Load_ahkFile(string AHK_FilePath, bool NewAHKSession = false, bool AddReturn = false) 116 | { 117 | _AHK ahk = new _AHK(); 118 | return ahk.Load_ahkFile(AHK_FilePath, NewAHKSession, AddReturn); 119 | } 120 | 121 | /// Load AHK Script from a String containing AHK Functions Into Current or New AHK Session 122 | /// AHK Script String containing AHK Commands 123 | /// option to restart AHK session, clearing previously saved hotkeys and variable values in memory 124 | /// Option to add Return in front of code added. Keeps from executing your script while loading. 125 | public static void Load_ahkString(string functionsAHK, bool NewAHKSession = false, bool AddReturn = false) 126 | { 127 | _AHK ahk = new _AHK(); 128 | ahk.Load_ahkString(functionsAHK, NewAHKSession, AddReturn); 129 | } 130 | 131 | /// 132 | /// Displays/Returns String with Whether AHK Session Has Been Initiated + # of AHK Files Loaded into Memory + AHK FilePaths Loaded 133 | /// 134 | public static string ahkSessionInfo(bool MsgBoxDisplay = false) 135 | { 136 | _AHK ahk = new _AHK(); 137 | return ahk.ahkSessionInfo(MsgBoxDisplay); 138 | } 139 | 140 | /// Load All AHK Scripts in Directory Path into New or Current AHK Instance 141 | /// Directory path of AHK files to load 142 | /// Option to search subdirectories underneath DirPath for AHK Files (default = false) 143 | /// Option to Reset AHK Instance, Clearing Previously Saved Hotkeys and Variable Values in Memory 144 | /// Option to add Return in front of code added. Keeps from executing your script while loading. 145 | /// Returns list of .AHK file paths loaded into current AHK Session 146 | public static List Load_ahkDir(string DirPath, bool Recurse = false, bool NewAHKSession = false, bool AddReturn = false) 147 | { 148 | _AHK ahk = new _AHK(); 149 | return ahk.Load_ahkDir(DirPath, Recurse, NewAHKSession, AddReturn); 150 | } 151 | 152 | /// Execute AHK Function Previously Loaded in Current AHK Session 153 | /// Name of Function to Call 154 | /// Parameter to pass into AHK function 155 | /// Parameter to pass into AHK function 156 | /// Parameter to pass into AHK function 157 | /// Parameter to pass into AHK function 158 | /// Parameter to pass into AHK function 159 | /// Parameter to pass into AHK function 160 | /// Parameter to pass into AHK function 161 | /// Parameter to pass into AHK function 162 | /// Parameter to pass into AHK function 163 | /// Parameter to pass into AHK function 164 | /// Returns value of function? Untested 165 | public static string Function(string FunctionName, string Param1 = null, string Param2 = null, string Param3 = null, string Param4 = null, string Param5 = null, string Param6 = null, string Param7 = null, string Param8 = null, string Param9 = null, string Param10 = null) // launch AHK function and return value if there is one 166 | { 167 | _AHK ahk = new _AHK(); 168 | return ahk.Function(FunctionName, Param1, Param2, Param3, Param4, Param5, Param6, Param7, Param8, Param9, Param10); 169 | } 170 | 171 | /// 172 | /// Checks to see if Function has been defined in AHK Session 173 | /// 174 | /// Name of Function To Check For 175 | /// 176 | public static bool FunctionExists(string FunctionName) 177 | { 178 | _AHK ahk = new _AHK(); 179 | return ahk.FunctionExists(FunctionName); 180 | } 181 | 182 | /// Execute Label/GoSub Command Loaded in Current AHK Session 183 | /// AHK Script Label to Execute 184 | /// Option to Confirm Label Exists in Memory Before Attempting To Execute 185 | public static void GoSub(string GoSubName, bool CheckIfExistsFirst = false) 186 | { 187 | _AHK ahk = new _AHK(); 188 | ahk.GoSub(GoSubName, CheckIfExistsFirst); 189 | } 190 | 191 | /// 192 | /// Checks to see if GoSub Label Exists in AHK Session 193 | /// 194 | /// 195 | /// 196 | public static bool LabelExists(string GoSubLabel) 197 | { 198 | _AHK ahk = new _AHK(); 199 | return ahk.LabelExists(GoSubLabel); 200 | } 201 | 202 | 203 | /// Function Used to Flag Whether AHK Function Uses ErrorLog Value 204 | /// Logs ErrorLevel Variables to Log if True, Otherwise Resets to Blank 205 | /// ErrorMessage From Function To Log if Problem Detected 206 | public static void ErrorLog_Setup(bool ErrorLogEnabled = true, string ErrorLogText = "") 207 | { 208 | _AHK ahk = new _AHK(); 209 | ahk.ErrorLog_Setup(ErrorLogEnabled, ErrorLogText); 210 | } 211 | 212 | 213 | //public static ErrorLogEntry errorLog = new ErrorLogEntry(); 214 | 215 | /// Used by AHK Functions to Log Last Script Command/Line Executed and Sets ErrorLevel Value If Detected 216 | /// AHK/C# Command with ErrorLevelMessage 217 | /// 218 | public static void ErrorLog(string ScriptLine, string ErrorLevelMsg = "") 219 | { 220 | _AHK ahk = new _AHK(); 221 | ahk.ErrorLog(ScriptLine, ErrorLevelMsg); 222 | } 223 | 224 | 225 | 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /_Expressions/_ClipboardExt.cs: -------------------------------------------------------------------------------- 1 | using sharpAHK; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace AHKExpressions 9 | { 10 | public static partial class AHKExpressions 11 | { 12 | // #region === Clipboard Extentions === 13 | 14 | /// 15 | /// Write Text to Clipboard 16 | /// 17 | /// Writes Text to Clipboard 18 | public static void ToClipboard(this string WriteText) 19 | { 20 | _AHK ahk = new _AHK(); 21 | ahk.ClipWrite(WriteText); 22 | } 23 | 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /_Expressions/_ControlsExt.cs: -------------------------------------------------------------------------------- 1 | using AHKExpressions; 2 | using sharpAHK; 3 | using System; 4 | using System.Collections.Generic; 5 | using System.Drawing; 6 | using System.Linq; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | using System.Windows.Forms; 10 | 11 | namespace AHKExpressions 12 | { 13 | public static partial class AHKExpressions 14 | { 15 | // === Controls === 16 | 17 | 18 | public static void Button_Image(Button button, string ImgPath, bool ImageLeft = true) 19 | { 20 | _AHK ahk = new _AHK(); 21 | Image image = ahk.ToImage(ImgPath); // convert input to Image format 22 | 23 | //=== Button Image: text far left - icon middle ==== (works) 24 | button.TextImageRelation = TextImageRelation.TextBeforeImage; 25 | button.BackgroundImageLayout = ImageLayout.Zoom; // adjust zoom to make button icon fit (works) 26 | button.BackgroundImage = image; 27 | 28 | if (ImageLeft) // image on left side of button 29 | { 30 | button.ImageAlign = ContentAlignment.MiddleRight; 31 | button.TextAlign = ContentAlignment.MiddleLeft; 32 | } 33 | if (!ImageLeft) // image on right side of button 34 | { 35 | button.ImageAlign = ContentAlignment.MiddleLeft; 36 | button.TextAlign = ContentAlignment.MiddleRight; 37 | } 38 | 39 | } 40 | 41 | 42 | // === Draggable Controls Extension === 43 | 44 | // Example Use: AnyControl.Draggable(true); 45 | 46 | /// 47 | /// Enabling/disabling dragging for control 48 | /// Source: https://www.codeproject.com/Tips/178587/Draggable-WinForms-Controls 49 | /// 50 | public static void Draggable(this Control control, bool Enable = true) 51 | { 52 | if (Enable) 53 | { 54 | // enable drag feature 55 | if (draggables.ContainsKey(control)) 56 | { // return if control is already draggable 57 | return; 58 | } 59 | // 'false' - initial state is 'not dragging' 60 | draggables.Add(control, false); 61 | 62 | // assign required event handlersnnn 63 | control.MouseDown += new MouseEventHandler(control_MouseDown); 64 | control.MouseUp += new MouseEventHandler(control_MouseUp); 65 | control.MouseMove += new MouseEventHandler(control_MouseMove); 66 | } 67 | else 68 | { 69 | // disable drag feature 70 | if (!draggables.ContainsKey(control)) 71 | { // return if control is not draggable 72 | return; 73 | } 74 | // remove event handlers 75 | control.MouseDown -= control_MouseDown; 76 | control.MouseUp -= control_MouseUp; 77 | control.MouseMove -= control_MouseMove; 78 | draggables.Remove(control); 79 | } 80 | } 81 | static void control_MouseDown(object sender, MouseEventArgs e) 82 | { 83 | mouseOffset = new System.Drawing.Size(e.Location); 84 | // turning on dragging 85 | draggables[(Control)sender] = true; 86 | } 87 | static void control_MouseUp(object sender, MouseEventArgs e) 88 | { 89 | // turning off dragging 90 | draggables[(Control)sender] = false; 91 | } 92 | static void control_MouseMove(object sender, MouseEventArgs e) 93 | { 94 | // only if dragging is turned on 95 | if (draggables[(Control)sender] == true) 96 | { 97 | // calculations of control's new position 98 | System.Drawing.Point newLocationOffset = e.Location - mouseOffset; 99 | ((Control)sender).Left += newLocationOffset.X; 100 | ((Control)sender).Top += newLocationOffset.Y; 101 | } 102 | } 103 | // TKey is control to drag, TValue is a flag used while dragging 104 | private static Dictionary draggables = 105 | new Dictionary(); 106 | private static System.Drawing.Size mouseOffset; 107 | 108 | 109 | 110 | 111 | 112 | 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /_Expressions/_DialogExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows.Forms; 7 | 8 | namespace AHKExpressions 9 | { 10 | public static partial class AHKExpressions 11 | { 12 | //#region === Dialogs === 13 | 14 | /// 15 | /// Behaves Same as MsgBox Command, Options are PreDefined Here for Faster Config 16 | /// 17 | /// Text to Display in MessageBox 18 | public static void MsgBox(this string Text) 19 | { 20 | MessageBox.Show(Text.ToString()); 21 | } 22 | 23 | /// yes/no user prompt 24 | /// 25 | /// 26 | public static DialogResult YesNoBox(this string Question, string Title) 27 | { 28 | //// EX: 29 | //var ResultValue = ahk.YesNoBox("Delete " + FileName + "?", "Delete File?"); 30 | //if (ResultValue.ToString() == "Yes") { ahk.FileDelete(FilePath); } 31 | 32 | return MessageBox.Show(Question, Title, MessageBoxButtons.YesNo); 33 | } 34 | 35 | /// yes/no/cancel prompt for user input 36 | /// 37 | /// 38 | public static DialogResult YesNoCancelBox(this string Question, string Title) // yes/no/cancel prompt for user input 39 | { 40 | //// EX: 41 | //var ResultValue = ahk.YesNoCancelBox("Delete ?", "Delete File?"); 42 | //if (ResultValue.ToString() == "Cancel") { ahk.MsgBox("Canceled"); } 43 | 44 | return MessageBox.Show(Question, Title, MessageBoxButtons.YesNoCancel); 45 | } 46 | 47 | 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /_Expressions/_ProcessesExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AHKExpressions 8 | { 9 | public static partial class AHKExpressions 10 | { 11 | // === Process === 12 | 13 | /// Runs an external program. 14 | /// A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), or system verb to launch (see remarks). If Target is a local file and no path was specified with it, A_WorkingDir will be searched first. If no matching file is found there, the system will search for and launch the file if it is integrated ("known"), e.g. by being contained in one of the PATH folders. To pass parameters, add them immediately after the program or document name. If a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases). 15 | /// The working directory for the launched item. Do not enclose the name in double quotes even if it contains spaces. If omitted, the script's own working directory (A_WorkingDir) will be used. 16 | /// Max: launch maximized | Min: launch minimized | Hide: launch hidden | UseErrorLevel: If the launch fails, this option skips the warning dialog, sets ErrorLevel to the word ERROR, and allows the current thread to continue. 17 | /// Returns OutputVarPID as string 18 | public static string Run(this string Target, string WorkingDir = "", string MinMaxHideUseErrorLevel = "") 19 | { 20 | string AHKLine = "Run, " + Target + "," + WorkingDir + "," + MinMaxHideUseErrorLevel + ", OutputVarPID"; // ahk line to execute 21 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 22 | string OutVar = Execute(AHKLine, "OutputVarPID"); // execute AHK code and return variable value 23 | return OutVar; 24 | 25 | // v1 ToDo 26 | /* 27 | public IntPtr _Run(string Target, string Arguments = "", bool Hidden = false) // run application path. includes win tools (Notepad, cmd, calc, word, paint, regedit, notepad++ as TARGET to launch) 28 | { 29 | IntPtr ApphWnd = new IntPtr(0); 30 | 31 | if (Target.ToUpper() == "NOTEPAD") { Target = Environment.SystemDirectory + "\\notepad.exe"; } 32 | if (Target.ToUpper() == "CMD" || Target.ToUpper() == "COMMAND") { Target = Environment.SystemDirectory + "\\cmd.exe"; } 33 | if (Target.ToUpper() == "CALC" || Target.ToUpper() == "CALCULATOR") { Target = Environment.SystemDirectory + "\\calc.exe"; } 34 | if (Target.ToUpper() == "WORD") { Target = Environment.SystemDirectory + "\\word.exe"; } 35 | if (Target.ToUpper() == "PAINT") { Target = Environment.SystemDirectory + "\\paint.exe"; } 36 | if (Target.ToUpper() == "REGEDIT") { Target = Environment.SystemDirectory + "\\regedit.exe"; } 37 | 38 | if (Target.ToUpper() == "NOTEPAD++") 39 | { 40 | Target = @"C:\Google Drive\AHK\Lib\Tool_Library\Office\Notepad++\App\Notepad++\Notepad++.exe"; 41 | if (!File.Exists(Target)) { Target = @"C:\Users\jason\Google Drive\AHK\Lib\Tool_Library\Office\Notepad++\App\Notepad++\Notepad++.exe"; } 42 | } 43 | 44 | if (Target.ToUpper().Contains("HTTP://")) //user trying to open url 45 | { 46 | Process proc; 47 | proc = System.Diagnostics.Process.Start(Target); 48 | proc.WaitForInputIdle(); 49 | try { ApphWnd = proc.MainWindowHandle; } 50 | catch { } 51 | return ApphWnd; 52 | } 53 | 54 | if (File.Exists(Target)) 55 | { 56 | FileInfo info = new FileInfo(Target); 57 | 58 | // check to see if target is a directory, if so 59 | FileAttributes attr = File.GetAttributes(Target); 60 | if ((attr & FileAttributes.Directory) == FileAttributes.Directory) 61 | { 62 | //it's a directory 63 | OpenDir(Target); 64 | return ApphWnd; 65 | } 66 | 67 | 68 | ProcessStartInfo startInfo = new ProcessStartInfo(); 69 | startInfo.WorkingDirectory = info.Directory.ToString(); 70 | startInfo.FileName = Target; 71 | startInfo.Arguments = Arguments; 72 | 73 | if (Hidden == true) 74 | { 75 | startInfo.WindowStyle = ProcessWindowStyle.Hidden; 76 | } 77 | 78 | Process proc; 79 | proc = Process.Start(startInfo); 80 | try { proc.WaitForInputIdle(); } 81 | catch { } 82 | 83 | try { ApphWnd = proc.MainWindowHandle; } 84 | catch { } 85 | return ApphWnd; 86 | } 87 | 88 | return ApphWnd; 89 | } 90 | */ 91 | 92 | 93 | 94 | } 95 | 96 | /// Runs an external program. RunWait will wait until the program finishes before continuing. 97 | /// A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), or system verb to launch (see remarks). If Target is a local file and no path was specified with it, A_WorkingDir will be searched first. If no matching file is found there, the system will search for and launch the file if it is integrated ("known"), e.g. by being contained in one of the PATH folders. To pass parameters, add them immediately after the program or document name. If a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases). 98 | /// The working directory for the launched item. Do not enclose the name in double quotes even if it contains spaces. If omitted, the script's own working directory (A_WorkingDir) will be used. 99 | /// Max: launch maximized | Min: launch minimized | Hide: launch hidden | UseErrorLevel: If the launch fails, this option skips the warning dialog, sets ErrorLevel to the word ERROR, and allows the current thread to continue. 100 | /// Returns OutputVarPID as string 101 | public static string RunWait(this string Target, string WorkingDir = "", string MinMaxHideUseErrorLevel = "") 102 | { 103 | string AHKLine = "RunWait, " + Target + "," + WorkingDir + "," + MinMaxHideUseErrorLevel + ", OutputVarPID"; // ahk line to execute 104 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 105 | string OutVar = Execute(AHKLine, "OutputVarPID"); // execute AHK code and return variable value 106 | 107 | // returns OutputVarPID 108 | return OutVar; 109 | 110 | // v1 ToDo 111 | /* 112 | public bool _RunWait(string ProcessPath, string Arguments = "", bool Hidden = false) // runs application and waits for the application to end before continuing 113 | { 114 | if (File.Exists(ProcessPath)) 115 | { 116 | Process process = new Process(); 117 | process.StartInfo.FileName = ProcessPath; 118 | process.StartInfo.Arguments = Arguments; 119 | process.StartInfo.ErrorDialog = true; 120 | //process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; 121 | if (Hidden == true) 122 | { 123 | process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 124 | } 125 | process.Start(); 126 | process.WaitForExit(); 127 | return true; 128 | } 129 | 130 | return false; 131 | } 132 | */ 133 | 134 | } 135 | 136 | 137 | /// Waits the specified amount of time before continuing. 138 | /// The amount of time to pause (in milliseconds) between 0 and 2147483647 (24 days), which can be an expression. 139 | public static void Sleep(this object DelayInMilliseconds) 140 | { 141 | string AHKLine = "Sleep, " + DelayInMilliseconds.ToString(); // ahk line to execute 142 | ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 143 | Execute(AHKLine); // execute AHK code and return variable value 144 | 145 | // v1 ToDo 146 | /* 147 | _Sleep(int SleepTime) // sleeps / idles for x seconds before continuing 148 | { 149 | Thread.Sleep(SleepTime); 150 | } 151 | */ 152 | 153 | } 154 | 155 | 156 | 157 | 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /_Expressions/_TreeViewExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows.Forms; 7 | 8 | namespace AHKExpressions 9 | { 10 | public static partial class AHKExpressions 11 | { 12 | 13 | // === TREEVIEW === 14 | 15 | /// Expand All Nodes in TreeView 16 | /// 17 | public static void Expand(this TreeView TV) 18 | { 19 | // expand search results in tree 20 | if (TV.InvokeRequired) 21 | { 22 | TV.BeginInvoke((MethodInvoker)delegate () { TV.ExpandAll(); }); 23 | } 24 | else 25 | { 26 | TV.ExpandAll(); 27 | } 28 | } 29 | 30 | /// 31 | /// Expand TreeNodes Below NodeLevel 32 | /// 33 | /// TreeView Control 34 | /// Level of Nodes to Expand 35 | public static void Expand_Level(this TreeView TV, int NodeLevel = 0) 36 | { 37 | List results = NodeList(TV, false); // return list of nodes (option for checked only) 38 | 39 | foreach (TreeNode node in results) 40 | { 41 | if (node.Level <= NodeLevel) 42 | { 43 | node.Expand(); 44 | } 45 | if (node.Level > NodeLevel) 46 | { 47 | node.Collapse(); 48 | } 49 | } 50 | } 51 | 52 | 53 | #region === TreeView: Return From Tree === 54 | 55 | // Return Data From TreeView 56 | 57 | /// Returns list of nodes in TreeView (Option to Return Checked Only) - option to return nodes on certain level 58 | /// 59 | /// 60 | /// 61 | public static List NodeList(this TreeView TV, bool CheckedOnly = false, int NodeLevel = -1) 62 | { 63 | ////Ex: 64 | 65 | //List results = tv.NodeList(treeView1, false); // return list of nodes (option for checked only) 66 | 67 | //foreach (TreeNode node in results) 68 | //{ 69 | // ahk.MsgBox(node.Text); 70 | //} 71 | 72 | 73 | List result = new List(); 74 | 75 | 76 | // create list of nodes to loop through 77 | List nodeList = new List(); // create list of all nodes in treeview to check 78 | foreach (TreeNode node in TV.Nodes) { nodeList.Add(node); } 79 | 80 | 81 | foreach (TreeNode node in nodeList) 82 | { 83 | 84 | if (NodeLevel != -1) 85 | { 86 | if (node.Level == NodeLevel) 87 | { 88 | if (CheckedOnly) 89 | { 90 | if (node.Checked) { result.Add(node); } 91 | } 92 | 93 | if (!CheckedOnly) { result.Add(node); } 94 | } 95 | continue; 96 | } 97 | 98 | 99 | 100 | // only return values that are checked 101 | if (CheckedOnly) 102 | { 103 | if (node.Checked) 104 | { 105 | result.Add(node); 106 | List kids = Nodes_Children(TV, node, CheckedOnly); 107 | foreach (TreeNode kid in kids) 108 | { 109 | result.Add(kid); 110 | } 111 | } 112 | 113 | if (!node.Checked) 114 | { 115 | List kids = Nodes_Children(TV, node, CheckedOnly); 116 | foreach (TreeNode kid in kids) 117 | { 118 | result.Add(kid); 119 | } 120 | } 121 | 122 | } 123 | 124 | // return all entries, checked + unchecked 125 | if (!CheckedOnly) 126 | { 127 | //MessageBox.Show(node.Text); 128 | result.Add(node); 129 | List kids = Nodes_Children(TV, node, CheckedOnly); 130 | foreach (TreeNode kid in kids) 131 | { 132 | result.Add(kid); 133 | } 134 | } 135 | 136 | } 137 | 138 | 139 | return result; 140 | } 141 | 142 | 143 | /// Recurse through treeview nodes, return list of child nodes 144 | /// 145 | /// 146 | /// 147 | public static List Nodes_Children(this TreeView TV, TreeNode treeNode, bool CheckedOnly = false) 148 | { 149 | List kids = new List(); 150 | 151 | if (treeNode == null) { return null; } //nothing to do if null value passed while user is clicking 152 | 153 | 154 | // update control text (from any thread) -- [ works in dll ] 155 | List nodeList = new List(); // create list of all nodes in treeview to check 156 | foreach (TreeNode tnz in treeNode.Nodes) { nodeList.Add(tnz); } 157 | 158 | 159 | // Print each child node recursively. 160 | foreach (TreeNode tn in nodeList) 161 | { 162 | // only return values that are checked 163 | if (CheckedOnly) 164 | { 165 | if (tn.Checked) 166 | { 167 | kids.Add(tn); 168 | List subkids = Nodes_Children(TV, tn, CheckedOnly); 169 | foreach (TreeNode kid in subkids) 170 | { 171 | kids.Add(kid); 172 | } 173 | } 174 | if (!tn.Checked) 175 | { 176 | List subkids = Nodes_Children(TV, tn, CheckedOnly); 177 | foreach (TreeNode kid in subkids) 178 | { 179 | kids.Add(kid); 180 | } 181 | } 182 | 183 | } 184 | 185 | // return all entries, checked + unchecked 186 | if (!CheckedOnly) 187 | { 188 | // Print the node. 189 | //MessageBox.Show(tn.Text); 190 | kids.Add(tn); 191 | List subkids = Nodes_Children(TV, tn, CheckedOnly); 192 | foreach (TreeNode kid in subkids) 193 | { 194 | kids.Add(kid); 195 | } 196 | 197 | } 198 | } 199 | 200 | return kids; 201 | } 202 | 203 | 204 | 205 | 206 | #endregion 207 | 208 | 209 | 210 | 211 | } 212 | } 213 | -------------------------------------------------------------------------------- /_Expressions/_XMLExt.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | using System.Xml; 8 | 9 | namespace AHKExpressions 10 | { 11 | public static partial class AHKExpressions 12 | { 13 | // === XML === 14 | 15 | 16 | // Helper method for getting inner text of named XML element (From File or XML String) 17 | static private string XMLGetValue(string XML_StringOrPath, string name, string defaultValue = "") 18 | { 19 | if (!File.Exists(XML_StringOrPath)) 20 | { 21 | XmlDocument doc = new XmlDocument(); 22 | doc.LoadXml(XML_StringOrPath); 23 | 24 | XmlElement elValue = doc.DocumentElement.SelectSingleNode(name) as XmlElement; 25 | return (elValue == null) ? defaultValue : elValue.InnerText; 26 | //return defaultValue; 27 | } 28 | else // xml file path passed in 29 | { 30 | try 31 | { 32 | XmlDocument docXML = new XmlDocument(); 33 | docXML.Load(XML_StringOrPath); 34 | XmlElement elValue = docXML.DocumentElement.SelectSingleNode(name) as XmlElement; 35 | return (elValue == null) ? defaultValue : elValue.InnerText; 36 | } 37 | catch 38 | { 39 | return defaultValue; 40 | } 41 | } 42 | 43 | 44 | } 45 | 46 | // Helper method to set inner text of named element. Creates document if it doesn't exist 47 | static public void XMLSetValue(string XML_FilePath, string name, string stringValue) 48 | { 49 | XmlDocument docXML = new XmlDocument(); 50 | XmlElement elRoot = null; 51 | if (!File.Exists(XML_FilePath)) 52 | { 53 | elRoot = docXML.CreateElement("root"); 54 | docXML.AppendChild(elRoot); 55 | } 56 | else 57 | { 58 | docXML.Load(XML_FilePath); 59 | elRoot = docXML.DocumentElement; 60 | } 61 | XmlElement value = docXML.DocumentElement.SelectSingleNode(name) as XmlElement; 62 | if (value == null) 63 | { 64 | value = docXML.CreateElement(name); 65 | elRoot.AppendChild(value); 66 | } 67 | value.InnerText = stringValue; 68 | docXML.Save(XML_FilePath); 69 | } 70 | 71 | 72 | 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /_sharpAHK/AHK.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using AutoHotkey.Interop.Util; 7 | using System.Windows.Forms; 8 | using System.IO; 9 | using System.Threading; 10 | using System.Text.RegularExpressions; 11 | using System.Drawing; 12 | using System.Reflection; 13 | using System.Data; 14 | using System.Diagnostics; 15 | using System.IO.Compression; 16 | using System.Security.Cryptography; 17 | using System.Runtime.InteropServices; 18 | using Microsoft.VisualBasic.FileIO; 19 | using Microsoft.VisualBasic.Devices; 20 | using System.Net; 21 | using AHKExpressions; 22 | using sharpAHK; 23 | using System.Drawing.Imaging; 24 | using System.Xml.Serialization; 25 | using System.Timers; 26 | using System.Configuration; 27 | using System.Data.SqlClient; 28 | 29 | 30 | 31 | namespace sharpAHK 32 | { 33 | /// 34 | /// sharpAHK : Library of AHK Driven/Inspired Methods 35 | /// 36 | public partial class _AHK 37 | { 38 | // To Do : 39 | // Function Library needs lots of testing (log of working / need work / known issues) 40 | // Need to merge v1 and v2 attempts (v1 = C# attempts to recreate AHK, v2 = AHK dll wrappers, in some cases v1 method is better) 41 | // Convert all variables to objects to allow multiple input formats (?) 42 | // Finish ErrorLogging + AutoLog option 43 | 44 | 45 | 46 | 47 | } 48 | 49 | 50 | 51 | } -------------------------------------------------------------------------------- /_sharpAHK/_Clipboard.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Windows.Forms; 7 | 8 | namespace sharpAHK 9 | { 10 | public partial class _AHK 11 | { 12 | // === Clipboard === 13 | 14 | /// 15 | /// Returns Contents of the OS's Clipboard. Writes to Clipboard if Value Provided in WriteText Param 16 | /// 17 | /// If Provided, Writes Text to Clipboard Instead of Returning Clipboard Contents 18 | /// Returns Contents of Clipboard with Option to Write New Clipboard Value 19 | public string Clipboard(string WriteText = "") 20 | { 21 | if (WriteText != "") { SetVar("clipboard", WriteText); return WriteText; } // user provided value to Write to Clipboard 22 | 23 | bool AHKMethod = true; 24 | 25 | if (AHKMethod) 26 | { 27 | string AHKLine = "OutputVar = %Clipboard%"; // ahk line to execute 28 | ErrorLog_Setup(false); // ErrorLevel Detection Disabled for this function in AHK 29 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 30 | return OutVar; 31 | } 32 | else // untested alternative clipboard function 33 | { 34 | string clipboard = ""; 35 | try 36 | { 37 | IDataObject ClipData = System.Windows.Forms.Clipboard.GetDataObject(); 38 | 39 | if (ClipData.GetDataPresent(DataFormats.Text)) 40 | { 41 | clipboard = System.Windows.Forms.Clipboard.GetData(DataFormats.Text).ToString(); 42 | } 43 | } 44 | catch { } 45 | return clipboard; 46 | } 47 | } 48 | 49 | /// 50 | /// Returns Entire Contents of Clipboard (Such as Formatting and Text) 51 | /// 52 | /// Returns String with Entire Contents of Clipboard 53 | public string ClipboardAll() 54 | { 55 | string AHKLine = "OutputVar = %ClipboardAll%"; // ahk line to execute 56 | ErrorLog_Setup(false); // ErrorLevel Detection Disabled for this function in AHK 57 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 58 | return OutVar; 59 | } 60 | 61 | /// 62 | /// Waits for Clipboard To Contain value, returns Clipboard contents 63 | /// 64 | /// Seconds to Wait Before ClipWait Times Out 65 | /// If False is More Selective, Waiting for Files/Text To Exist 66 | /// 67 | public string ClipWait(int SecondsToWait = 5) 68 | { 69 | string clipboard = ""; 70 | SetVar("clipboard", clipboard); // clear out clipboard 71 | 72 | //if (AnyData) { AnyDataOnClipboard = 1; } 73 | //string AHKLine = @"ClipWait, " + SecondsToWait + "," + AnyDataOnClipboard; // ahk line to execute 74 | //ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 75 | 76 | do // loop until clipboard isn't empty 77 | { 78 | clipboard = Clipboard(); // returns clipboard value 79 | 80 | } while (clipboard == ""); 81 | 82 | return clipboard; 83 | } 84 | 85 | /// 86 | /// Clears Contents of Clipboard 87 | /// 88 | public void ClipboardClear() 89 | { 90 | SetVar("clipboard", ""); 91 | } 92 | 93 | /// 94 | /// Write Text to Clipboard (Blank to Clear) 95 | /// 96 | /// Writes Text to Clipboard 97 | public void ClipWrite(string WriteText = "") 98 | { 99 | SetVar("clipboard", WriteText); 100 | 101 | // v1 ToDo 102 | /* 103 | _ClipboardWrite(string WriteText) // writes text to user's clipboard 104 | { 105 | System.Windows.Forms.Clipboard.SetDataObject(WriteText); 106 | } 107 | */ 108 | 109 | } 110 | 111 | /// 112 | /// Adds One or More Files to Windows Clipboard, Ready to Paste in Explorer 113 | /// 114 | /// FileList can be a Single File Path (as string) or List of File Paths (strings) 115 | /// 116 | public bool Clipboard_Files(object fileList) 117 | { 118 | // determine if FilePath (string) or List of Files was passed in 119 | string VarType = fileList.GetType().ToString(); 120 | //MsgBox(VarType); 121 | bool isFile = false; bool isList = false; 122 | if (VarType == "System.String") { isFile = true; } 123 | if (VarType == "System.Collections.Generic.List`1[System.String]") { isList = true; } 124 | 125 | System.Collections.Specialized.StringCollection paths = new System.Collections.Specialized.StringCollection(); 126 | 127 | if (isList) // list of files passed in as string list 128 | { 129 | List files = fileList as List; 130 | foreach (var item in files) 131 | { 132 | paths.Add(fileList.ToString()); 133 | } 134 | try { System.Windows.Forms.Clipboard.SetFileDropList(paths); return true; } 135 | catch { return false; } 136 | } 137 | 138 | if (isFile) // single file passed in as string 139 | { 140 | paths.Add(fileList.ToString()); 141 | try { System.Windows.Forms.Clipboard.SetFileDropList(paths); return true; } 142 | catch { return false; } 143 | } 144 | 145 | return false; 146 | } 147 | 148 | 149 | 150 | } 151 | } 152 | -------------------------------------------------------------------------------- /_sharpAHK/_DateTime.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace sharpAHK 9 | { 10 | public partial class _AHK 11 | { 12 | // === DateTime === 13 | 14 | /// Compare Date to DateToCompare, Returns either Earlier, Same, or Later as String 15 | /// Date To Compare 16 | /// Date to Compare Against 17 | /// Returns either Earlier/Same/Later as String 18 | public string DateTimeCompare(DateTime Date, DateTime DateToCompare) 19 | { 20 | //DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0); 21 | //DateTime date2 = new DateTime(2009, 8, 2, 0, 0, 0); 22 | 23 | int result = DateTime.Compare(Date, DateToCompare); 24 | 25 | if (result < 0) 26 | return "Earlier"; // 1 is before 2 27 | else if (result == 0) 28 | return "Same"; // 1 = 2 29 | else 30 | return "Later"; // 1 is later than 2 31 | } 32 | 33 | /// Verify/Format dates before inserting into sql db 34 | /// DateTime String To Verify/Convert to DateTime 35 | public DateTime ValidTime(string InTime) 36 | { 37 | bool Valid = IsValidSqlDatetime(InTime); 38 | 39 | if (Valid) 40 | { 41 | DateTime Converted = Convert.ToDateTime(InTime); 42 | return Converted; 43 | } 44 | 45 | //if (!Valid) 46 | DateTime PlaceHolderTime = new DateTime(1900, 1, 1); 47 | return PlaceHolderTime; 48 | } 49 | 50 | /// Checks to see if Date is a Valid SQL Date 51 | /// Date as string to Check 52 | /// Returns True if Date is Valid in SQL 53 | public bool IsValidSqlDatetime(string DateString) 54 | { 55 | bool valid = false; 56 | DateTime testDate = DateTime.MinValue; 57 | DateTime minDateTime = DateTime.MaxValue; 58 | DateTime maxDateTime = DateTime.MinValue; 59 | 60 | minDateTime = new DateTime(1753, 1, 1); 61 | maxDateTime = new DateTime(9999, 12, 31, 23, 59, 59, 997); 62 | 63 | if (DateTime.TryParse(DateString, out testDate)) 64 | { 65 | if (testDate >= minDateTime && testDate <= maxDateTime) 66 | { 67 | valid = true; 68 | } 69 | } 70 | 71 | return valid; 72 | } 73 | 74 | 75 | 76 | // === Compare Time === 77 | 78 | //bool beforeTime = BeforeCurrentTime("11:00:00 AM"); 79 | //bool afterTime = AfterCurrentTime("11:00:00 AM"); 80 | //ahk.MsgBox("Before Time = " + beforeTime.ToString()); 81 | //ahk.MsgBox("After Time = " + afterTime.ToString()); 82 | 83 | /// 84 | /// compares timestamp string to current time, returns true if timestamp is before current time 85 | /// 86 | /// 87 | /// 88 | public bool BeforeCurrentTime(string TimeToCompare = "11:00:00 AM") 89 | { 90 | DateTime t1 = DateTime.Now; 91 | DateTime t2 = Convert.ToDateTime(TimeToCompare); 92 | int i = DateTime.Compare(t1, t2); 93 | 94 | //if t1 is less than t2 then result is Less than zero 95 | //if t1 equals t2 then result is Zero 96 | //if t1 is greater than t2 then result isGreater zero 97 | 98 | if (i > 0) { return false; } 99 | if (i < 0) { return true; } 100 | return false; 101 | } 102 | 103 | /// 104 | /// compares timestamp string to current time, returns true if timestamp is after current time 105 | /// 106 | /// 107 | /// 108 | public bool AfterCurrentTime(string TimeToCompare = "11:00:00 AM") 109 | { 110 | DateTime t1 = DateTime.Now; 111 | DateTime t2 = Convert.ToDateTime("11:00:00 AM"); 112 | int i = DateTime.Compare(t1, t2); 113 | 114 | //if t1 is less than t2 then result is Less than zero 115 | //if t1 equals t2 then result is Zero 116 | //if t1 is greater than t2 then result isGreater zero 117 | 118 | if (i > 0) { return true; } 119 | if (i < 0) { return false; } 120 | return false; 121 | } 122 | 123 | 124 | /// 125 | /// Returns difference between two dates (in Minutes) 126 | /// 127 | /// First Date/Time - Can Pass in String or DateTime Var 128 | /// Date/Time to compare to first - Can Pass in String or DateTime Var 129 | /// Returns the Number of Min Between DateTime1 and DateTime2 130 | public int TimeDiff_Min(object DateTime1, object DateTime2) 131 | { 132 | 133 | DateTime dateTime11 = ToDateTime(DateTime1.ToString()); 134 | DateTime dateTime22 = ToDateTime(DateTime2.ToString()); 135 | 136 | TimeSpan diff = dateTime11 - dateTime22; 137 | 138 | double totalMinutes = diff.TotalMinutes; 139 | int min = ToInt(totalMinutes); 140 | 141 | //string timeDiff = diff.ToString(); 142 | return min; 143 | } 144 | 145 | 146 | // !!! finish 147 | 148 | /// 149 | /// 150 | /// 151 | /// 152 | /// 153 | public void Time_Difference(DateTime date1, DateTime date2) 154 | { 155 | //DateTime date1 = dateTimePicker1.Value; 156 | //DateTime date2 = dateTimePicker2.Value; 157 | 158 | TimeSpan difference = date2 - date1; 159 | string days = "Days: " + difference.TotalDays.ToString(); 160 | string hours = "Hours: " + difference.TotalHours.ToString(); 161 | string minutes = "Minutes: " + difference.TotalMinutes.ToString(); 162 | string seconds = "Seconds: " + difference.TotalSeconds.ToString(); 163 | string milliseconds = "Milliseconds: " + difference.TotalMilliseconds.ToString(); 164 | 165 | // v1 ToDo 166 | /* 167 | // difference between two dates (currently returns in minutes) 168 | string timeDiff(object dateTime1, object dateTime2) 169 | { 170 | 171 | DateTime dateTime11 = ToDateTime(dateTime1.ToString()); 172 | DateTime dateTime22 = ToDateTime(dateTime2.ToString()); 173 | 174 | TimeSpan diff = dateTime11 - dateTime22; 175 | //if (diff < 0) 176 | // { 177 | // diff = diff + TimeSpan.FromDays(1); 178 | // } 179 | 180 | double totalMinutes = diff.TotalMinutes; 181 | int min = ToInt(totalMinutes); 182 | 183 | string timeDiff = diff.ToString(); 184 | return timeDiff; 185 | } 186 | */ 187 | 188 | } 189 | 190 | 191 | 192 | // === Convert Time Formats === 193 | 194 | 195 | /// 196 | /// Convert Milliseconds into Minutes 197 | /// 198 | /// Millisecond Value to Convert 199 | /// Returns Minutes as Int 200 | public int MsToMin(int TimeMS) 201 | { 202 | try 203 | { 204 | TimeSpan t = TimeSpan.FromMilliseconds(TimeMS); 205 | return (int)t.TotalMinutes; 206 | } 207 | catch (Exception ex) 208 | { 209 | //WriteNote("Unexpected error - " + ex.Message.ToString()); 210 | return -1; 211 | } 212 | } 213 | 214 | /// 215 | /// Convert Milliseconds into Seconds 216 | /// 217 | /// Millisecond Value to Convert 218 | /// Returns Seconds as Int 219 | public int MsToSeconds(int TimeMS) 220 | { 221 | try 222 | { 223 | TimeSpan t = TimeSpan.FromMilliseconds(TimeMS); 224 | return (int)t.TotalSeconds; 225 | } 226 | catch (Exception ex) 227 | { 228 | //WriteNote("Unexpected error - " + ex.Message.ToString()); 229 | return -1; 230 | } 231 | } 232 | 233 | /// 234 | /// Convert Milliseconds into Hours 235 | /// 236 | /// Millisecond Value to Convert 237 | /// Returns Hours as Int 238 | public int MsToHours(int TimeMS) 239 | { 240 | try 241 | { 242 | TimeSpan t = TimeSpan.FromMilliseconds(TimeMS); 243 | return (int)t.TotalHours; 244 | } 245 | catch (Exception ex) 246 | { 247 | //WriteNote("Unexpected error - " + ex.Message.ToString()); 248 | return -1; 249 | } 250 | } 251 | 252 | /// 253 | /// Convert Milliseconds into Days 254 | /// 255 | /// Millisecond Value to Convert 256 | /// Returns Days as Int 257 | public int MsToDays(int TimeMS) 258 | { 259 | try 260 | { 261 | TimeSpan t = TimeSpan.FromMilliseconds(TimeMS); 262 | return (int)t.TotalDays; 263 | } 264 | catch (Exception ex) 265 | { 266 | //WriteNote("Unexpected error - " + ex.Message.ToString()); 267 | return -1; 268 | } 269 | } 270 | 271 | 272 | public static Stopwatch stopwatch = new Stopwatch(); 273 | 274 | /// 275 | /// Start/Stop StopWatch Timer 276 | /// 277 | /// 278 | /// 279 | public string StopWatch(bool Start = true) 280 | { 281 | if (Start) { stopwatch = new Stopwatch(); stopwatch.Start(); } 282 | else { stopwatch.Stop(); } 283 | return StringSplit(stopwatch.Elapsed.ToString(), ".", 0); 284 | } 285 | 286 | } 287 | } 288 | -------------------------------------------------------------------------------- /_sharpAHK/_Encryption.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Security.Cryptography; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace sharpAHK 10 | { 11 | public partial class _AHK 12 | { 13 | // === Encryption === 14 | 15 | //txtEncrypted.Text = Crypt.Encrypt(txtToEncrypt.Text, txtKey.Text); 16 | //txtDecrypted.Text = Crypt.Decrypt(txtEncrypted.Text, txtKey.Text); 17 | 18 | // Source: http://stackoverflow.com/questions/10168240/encrypting-decrypting-a-string-in-c-sharp 19 | // Credit: CraigTP 20 | 21 | /// Encrypt String Using passPhrase to Decrypt 22 | /// String to Encrypt 23 | /// Password to Decrypt Later 24 | public string Encrypt(string plainText, string passPhrase) 25 | { 26 | // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text 27 | // so that the same Salt and IV values can be used when decrypting. 28 | var saltStringBytes = Generate256BitsOfRandomEntropy(); 29 | var ivStringBytes = Generate256BitsOfRandomEntropy(); 30 | var plainTextBytes = Encoding.UTF8.GetBytes(plainText); 31 | using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations)) 32 | { 33 | var keyBytes = password.GetBytes(Keysize / 8); 34 | using (var symmetricKey = new RijndaelManaged()) 35 | { 36 | symmetricKey.BlockSize = 256; 37 | symmetricKey.Mode = CipherMode.CBC; 38 | symmetricKey.Padding = PaddingMode.PKCS7; 39 | using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes)) 40 | { 41 | using (var memoryStream = new MemoryStream()) 42 | { 43 | using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) 44 | { 45 | cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); 46 | cryptoStream.FlushFinalBlock(); 47 | // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes. 48 | var cipherTextBytes = saltStringBytes; 49 | cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray(); 50 | cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray(); 51 | memoryStream.Close(); 52 | cryptoStream.Close(); 53 | return Convert.ToBase64String(cipherTextBytes); 54 | } 55 | } 56 | } 57 | } 58 | } 59 | } 60 | 61 | /// Decrypts an Encrypted String using passphrase 62 | /// Encryptd String to Decrypt 63 | /// Password to Decrypt 64 | public string Decrypt(string cipherText, string passPhrase) 65 | { 66 | try 67 | { 68 | // Get the complete stream of bytes that represent: 69 | // [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText] 70 | var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText); 71 | // Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes. 72 | var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray(); 73 | // Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes. 74 | var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray(); 75 | // Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string. 76 | var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray(); 77 | 78 | using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations)) 79 | { 80 | var keyBytes = password.GetBytes(Keysize / 8); 81 | using (var symmetricKey = new RijndaelManaged()) 82 | { 83 | symmetricKey.BlockSize = 256; 84 | symmetricKey.Mode = CipherMode.CBC; 85 | symmetricKey.Padding = PaddingMode.PKCS7; 86 | using (var decryptor = symmetricKey.CreateDecryptor(keyBytes, ivStringBytes)) 87 | { 88 | using (var memoryStream = new MemoryStream(cipherTextBytes)) 89 | { 90 | using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) 91 | { 92 | var plainTextBytes = new byte[cipherTextBytes.Length]; 93 | var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); 94 | memoryStream.Close(); 95 | cryptoStream.Close(); 96 | return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); 97 | } 98 | } 99 | } 100 | } 101 | } 102 | 103 | } 104 | catch 105 | { 106 | // Invalid Key Provided 107 | return null; 108 | } 109 | } 110 | 111 | 112 | // This constant is used to determine the keysize of the encryption algorithm in bits. 113 | // We divide this by 8 within the code below to get the equivalent number of bytes. 114 | private const int Keysize = 256; 115 | 116 | /// 117 | /// This constant determines the number of iterations for the password bytes generation function. 118 | /// 119 | private const int DerivationIterations = 1000; 120 | 121 | /// 122 | /// Used by Encrypt Function 123 | /// 124 | /// 125 | private byte[] Generate256BitsOfRandomEntropy() 126 | { 127 | var randomBytes = new byte[32]; // 32 Bytes will give us 256 bits. 128 | using (var rngCsp = new RNGCryptoServiceProvider()) 129 | { 130 | // Fill the array with cryptographically secure random bytes. 131 | rngCsp.GetBytes(randomBytes); 132 | } 133 | return randomBytes; 134 | } 135 | 136 | 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /_sharpAHK/_INI.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace sharpAHK 9 | { 10 | public partial class _AHK 11 | { 12 | #region === INI === 13 | 14 | /// Deletes a value from a standard format .ini file. 15 | /// The name of the .ini file, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. 16 | /// The section name in the .ini file, which is the heading phrase that appears in square brackets (do not include the brackets in this parameter). 17 | /// The key name in the .ini file. If omitted, the entire Section will be deleted. 18 | public bool IniDelete(string IniPath, string Section, string Key = "") 19 | { 20 | string filename = IniPath.Replace(",", "`,"); 21 | string section = Section.Replace(",", "`,"); 22 | string key = Key.Replace(",", "`,"); 23 | 24 | string AHKLine = "IniDelete, " + filename + "," + section + "," + key; // ahk line to execute 25 | ErrorLog_Setup(true, "Error Deleting INI Key In: " + filename); // ErrorLevel Detection Enabled for this function in AHK 26 | Execute(AHKLine); // execute AHK code and return variable value 27 | 28 | if (!ahkGlobal.ErrorLevel) { return true; } // no error level - return true for success 29 | else { throw new System.InvalidOperationException(ahkGlobal.ErrorLevelMsg); } // throw exception on AHK error 30 | //return false; // error level detected - success = false 31 | } 32 | 33 | /// Reads a value from a standard format .ini file. 34 | /// The name of the .ini file, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. 35 | /// The section name in the .ini file, which is the heading phrase that appears in square brackets (do not include the brackets in this parameter). 36 | /// The key name in the .ini file. 37 | /// The value to store in OutputVar if the requested key is not found. If omitted, it defaults to the word ERROR. To store a blank value (empty string), specify %A_Space%. 38 | public string IniRead(string IniPath, string Section, string Key, string Default = "") 39 | { 40 | if (!File.Exists(IniPath)) { return ""; } 41 | 42 | 43 | string filename = IniPath.Replace(",", "`,"); 44 | string section = Section.Replace(",", "`,"); 45 | string key = Key.Replace(",", "`,"); 46 | string DEfault = Default.Replace(",", "`,"); 47 | 48 | //string fileName = StringReplace(Filename, "%", "`%", "ALL"); // fix illegal ahk chars 49 | 50 | string AHKLine = "IniRead, OutputVar, " + filename + "," + section + "," + key + "," + DEfault; // ahk line to execute 51 | ErrorLog_Setup(true, "Error Reading INI: " + filename); // ErrorLevel Detection Enabled for this function in AHK 52 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 53 | 54 | //if (ahkGlobal.ErrorLevel) { throw new System.InvalidOperationException(ahkGlobal.ErrorLevelMsg); } // throw exception on AHK error 55 | return OutVar; 56 | } 57 | 58 | /// Writes a value to a standard format .ini file. 59 | /// The string or number that will be written to the right of Key's equal sign (=). If the text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability. 60 | /// The name of the .ini file, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. 61 | /// The section name in the .ini file, which is the heading phrase that appears in square brackets (do not include the brackets in this parameter). 62 | /// The key name in the .ini file. 63 | public bool IniWrite(object Value, string IniPath, string Section, string Key) 64 | { 65 | if (Value == null) { Value = ""; } 66 | //throw new System.InvalidOperationException("Value is NULL"); 67 | if (IniPath == null) { throw new System.InvalidOperationException("IniPath Cannot be Null"); } 68 | 69 | //string filename = FileName(IniPath); string filedir = DirName(IniPath); 70 | 71 | if (IniPath.Contains("!")) { IniPath = IniPath.Replace("!", ""); } 72 | //if (IniPath.Contains(":")) { IniPath = IniPath.Replace(":", "-"); } 73 | if (IniPath.Contains("%")) { IniPath = IniPath.Replace("%", ""); } 74 | if (IniPath.Contains("/")) { IniPath = IniPath.Replace("/", " "); } 75 | 76 | string filename = IniPath.Replace(",", "`,"); 77 | string section = Section.Replace(",", "`,"); 78 | string key = Key.Replace(",", "`,"); 79 | string value = Value.ToString().Replace(",", "`,"); 80 | 81 | string AHKLine = "IniWrite, " + value + "," + filename + "," + section + "," + key; // ahk line to execute 82 | ErrorLog_Setup(true, "Error Deleting INI Key In: " + filename); // ErrorLevel Detection Enabled for this function in AHK 83 | Execute(AHKLine); // execute AHK code and return variable value 84 | 85 | if (!ahkGlobal.ErrorLevel) { return true; } // no error level - return true for success 86 | else { throw new System.InvalidOperationException(ahkGlobal.ErrorLevelMsg + " | " + ahkGlobal.ErrorLevelValue); } 87 | //return false; // error level detected - success = false 88 | } 89 | 90 | /// 91 | /// Reads .URL File and Returns Web Address 92 | /// 93 | /// FilePath to .URL File to Read 94 | /// Returns Link Found in .URL File 95 | public string URL_Read(string URLFile) 96 | { 97 | string URL = IniRead(URLFile, "InternetShortcut", "URL"); 98 | return URL; 99 | } 100 | 101 | /// 102 | /// Writes .URL File Link to WebSite 103 | /// 104 | /// Name of the Site to Save Link To 105 | /// Directory to Save New URL File To 106 | /// WebSite Address to Write to new URL File 107 | public void URL_Write(string linkName, string SaveDir, string linkURL) // write URL link file to local folder 108 | { 109 | IniWrite(linkURL, SaveDir + "\\" + linkName + ".url", "InternetShortcut", "URL"); 110 | } 111 | 112 | 113 | #endregion 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /_sharpAHK/_Launch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace sharpAHK 9 | { 10 | public partial class _AHK 11 | { 12 | 13 | /// 14 | /// Parse Application's CommandLine Parameters - Return Parsed Object 15 | /// 16 | /// 17 | public static CmdLine CommandLineParams() 18 | { 19 | string InLine = ""; 20 | //==== Command Line Parameters ================= 21 | int c = Environment.GetCommandLineArgs().Count(); 22 | if (c > 0) 23 | { 24 | for (int i = 0; i <= (c - 1); i++) 25 | { 26 | string[] args = Environment.GetCommandLineArgs(); 27 | 28 | if (InLine != "") { InLine = InLine + "|" + args[i]; } 29 | else { InLine = args[i]; } 30 | } 31 | } 32 | 33 | _AHK ahk = new _AHK(); 34 | string ThisAppEXE = ahk.StringSplit(InLine, "|", 0); 35 | string AppName = ahk.StringSplit(InLine, "|", 1); 36 | string FilePath = ahk.StringSplit(InLine, "|", 2); 37 | string DirPath = ""; 38 | 39 | if (File.Exists(AppName)) { FilePath = AppName; AppName = ""; } 40 | 41 | if (ThisAppEXE == AppName) { AppName = ""; } 42 | if (ThisAppEXE == FilePath) { FilePath = ""; } 43 | 44 | if (Directory.Exists(FilePath)) { DirPath = FilePath; FilePath = ""; } 45 | 46 | CmdLine cmd = new CmdLine(); 47 | cmd.AppName = AppName; 48 | cmd.FilePath = FilePath; 49 | cmd.ThisExePath = ThisAppEXE; 50 | cmd.DirPath = DirPath; 51 | 52 | return cmd; 53 | } 54 | 55 | /// 56 | /// Contains CommandLine Parameter Details 57 | /// 58 | public class CmdLine 59 | { 60 | public string ThisExePath; 61 | public string AppName; 62 | public string FilePath; 63 | public string DirPath; 64 | } 65 | 66 | 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /_sharpAHK/_Math.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace sharpAHK 8 | { 9 | public partial class _AHK 10 | { 11 | #region === Math === 12 | 13 | ///// Sets a variable to the sum of itself plus the given value (can also add or subtract time from a date-time value). Synonymous with: var += value 14 | ///// The variable upon which to operate. 15 | ///// Any integer, floating point number, or expression 16 | ///// If present, this parameter directs the command to add Value to Var, treating Var as a date-time stamp in the YYYYMMDDHH24MISS format and treating Value as the integer or floating point number of units to add (specify a negative number to perform subtraction). TimeUnits can be either Seconds, Minutes, Hours, or Days (or just the first letter of each of these). If Var is an empty variable, the current time will be used in its place. If Var contains an invalid timestamp or a year prior to 1601, or if Value is non-numeric, Var will be made blank to indicate the problem. The built-in variable A_Now contains the current local time in YYYYMMDDHH24MISS format. To calculate the amount of time between two timestamps, use EnvSub. 17 | //public string EnvAdd(string Var, string Value, string TimeUnits = "") // Not finished 18 | //{ 19 | // //string AHKLine = "EnvAdd, OutputVar, " + Value + "," + Count; // ahk line to execute 20 | // //ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 21 | // //string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 22 | // //return OutVar; 23 | // return ""; 24 | //} 25 | 26 | ///// Sets a variable to itself divided by the given value. Synonymous with: var /= value 27 | ///// The variable upon which to operate. 28 | ///// Any integer, floating point number, or expression. 29 | //public string EnvDiv(string Var, string Value) // Not finished 30 | //{ 31 | // //string AHKLine = "OutputVar, " + Value + "," + Count; // ahk line to execute 32 | // //ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 33 | // //string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 34 | // //return OutVar; 35 | // return ""; 36 | //} 37 | 38 | ///// Sets a variable to itself minus the given value (can also compare date-time values). Synonymous with: var -= value 39 | ///// The variable upon which to operate. 40 | ///// Any integer, floating point number, or expression. 41 | ///// If present, this parameter directs the command to subtract Value from Var as though both of them are date-time stamps in the YYYYMMDDHH24MISS format. TimeUnits can be either Seconds, Minutes, Hours, or Days (or just the first letter of each of these). If Value is blank, the current time will be used in its place. Similarly, if Var is an empty variable, the current time will be used in its place. The result is always rounded down to the nearest integer. For example, if the actual difference between two timestamps is 1.999 days, it will be reported as 1 day. If higher precision is needed, specify Seconds for TimeUnits and divide the result by 60.0, 3600.0, or 86400.0. If either Var or Value is an invalid timestamp or contains a year prior to 1601, Var will be made blank to indicate the problem. The built-in variable A_Now contains the current local time in YYYYMMDDHH24MISS format. To precisely determine the elapsed time between two events, use the A_TickCount method because it provides millisecond precision. To add or subtract a certain number of seconds, minutes, hours, or days from a timestamp, use EnvAdd (subtraction is achieved by adding a negative number). 42 | //public string EnvSub(string Var, string Value, string TimeUnits = "") // Not finished 43 | //{ 44 | // //string AHKLine = "OutputVar, " + Value + "," + Count; // ahk line to execute 45 | // //ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 46 | // //string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 47 | // //return OutVar; 48 | // return ""; 49 | //} 50 | 51 | ///// Sets a variable to itself times the given value. Synonymous with: var *= value 52 | ///// The variable upon which to operate. 53 | ///// Any integer, floating point number, or expression. 54 | //public string EnvMult(string Var, string Value) // Not finished 55 | //{ 56 | // //string AHKLine = "OutputVar, " + Value + "," + Count; // ahk line to execute 57 | // //ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 58 | // //string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 59 | // //return OutVar; 60 | // return ""; 61 | //} 62 | 63 | /// Generates a pseudo-random number. 64 | /// The smallest number that can be generated, which can be negative, floating point, or an expression. If omitted, the smallest number will be 0. The lowest allowed value is -2147483648 for integers, but floating point numbers have no restrictions. 65 | /// The largest number that can be generated, which can be negative, floating point, or an expression. If omitted, the largest number will be 2147483647 (which is also the largest allowed integer value -- but floating point numbers have no restrictions). 66 | public string Random(string Min = "", string Max = "") 67 | { 68 | string AHKLine = "Random, OutputVar, " + Min + "," + Max; // ahk line to execute 69 | ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 70 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 71 | return OutVar; 72 | } 73 | 74 | /// Reseeding can improve the quality/security of generated random numbers - affects all subsequently generated random numbers. 75 | /// This mode reseeds the random number generator with NewSeed (which can be an expression). This affects all subsequently generated random numbers. NewSeed should be an integer between 0 and 4294967295 (0xFFFFFFFF). Reseeding can improve the quality/security of generated random numbers, especially when NewSeed is a genuine random number rather than one of lesser quality such as a pseudo-random number. Generally, reseeding does not need to be done more than once. If reseeding is never done by the script, the seed starts off as the low-order 32-bits of the 64-bit value that is the number of 100-nanosecond intervals since January 1, 1601. This value travels from 0 to 4294967295 every ~7.2 minutes. 76 | public void Random_NewSeed(string NewSeed = "") 77 | { 78 | string AHKLine = "Random, , " + NewSeed; // ahk line to execute 79 | ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 80 | Execute(AHKLine); // execute AHK code and return variable value 81 | } 82 | 83 | /// Sets the format of integers and floating point numbers generated by math operations. 84 | /// Must be either IntegerFast, FloatFast, Integer, or Float 85 | /// For NumberType Integer or IntegerFast, specify H or HEX for hexadecimal, or D for decimal. Hexadecimal numbers all start with the prefix 0x (e.g. 0xFF). For NumberType Float or FloatFast, specify TotalWidth.DecimalPlaces (e.g. 0.6). In v1.0.46.11+, the letter "e" may be appended to produce scientific notation; e.g. 0.6e or 0.6E (using uppercase produces an uppercase E in each number instead of lowercase). Note: In AutoHotkey 1.x, scientific notation must include a decimal point; e.g. 1.0e1 is valid but not 1e1. TotalWidth is typically 0 to indicate that number should not have any blank or zero padding. If a higher value is used, numbers will be padded with spaces or zeroes (see remarks) to make them that wide. DecimalPlaces is the number of decimal places to display (rounding will occur). If blank or zero, neither a decimal portion nor a decimal point will be displayed, that is, floating point results are displayed as integers rather than a floating point number. The starting default is 6. Padding: If TotalWidth is high enough to cause padding, spaces will be added on the left side; that is, each number will be right-justified. To use left-justification instead, precede TotalWidth with a minus sign. To pad with zeroes instead of spaces, precede TotalWidth with a zero (e.g. 06.2). 86 | public void SetFormat(string NumberType, string Format) 87 | { 88 | string AHKLine = "SetFormat," + NumberType + "," + Format; // ahk line to execute 89 | ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 90 | Execute(AHKLine); // execute AHK code and return variable value 91 | } 92 | 93 | /// Performs miscellaneous math functions, bitwise operations, and tasks such as ASCII/Unicode conversion. 94 | /// See AHK Documentation For Options 95 | /// See AHK Documentation For Options 96 | /// See AHK Documentation For Options 97 | public string Transform(string Cmd, string Value1, string Value2 = "") 98 | { 99 | string AHKLine = "Transform, OutputVar, " + Cmd + "," + Value1 + "," + Value2; // ahk line to execute 100 | ErrorLog_Setup(false); // ErrorLevel Detection Enabled for this function in AHK 101 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 102 | return OutVar; 103 | } 104 | 105 | /// 106 | /// Returns the Remainder Value when Dividing Value, ex: 10/3 = remainder of 1 107 | /// 108 | /// Whole Number to Divide 109 | /// Value to Divide ValueToDivide by 110 | /// Returns Remaining Values that won't define evenly 111 | public int Remainder(int ValueToDivide, int DivideBy) 112 | { 113 | return ValueToDivide % DivideBy; 114 | } 115 | 116 | 117 | #endregion 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /_sharpAHK/_Monitor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace sharpAHK 8 | { 9 | public partial class _AHK 10 | { 11 | // === Monitors === 12 | 13 | /// Retrieves screen resolution, multi-monitor info, dimensions of system objects, and other system properties. 14 | /// MonitorCount | MonitorPrimary | Monitor, N | MonitorWorkArea, N | (See Documentation For Numeric Options) 15 | /// Additional Param for SysGet 16 | public string SysGet(string SubCommand, string Param3 = "") 17 | { 18 | return ahkReturn("SysGet, OutputVar, " + SubCommand + "," + Param3); 19 | } 20 | 21 | /// Retrieves the total number of monitors. Unlike SM_CMONITORS mentioned in the table below, MonitorCount includes all monitors, even those not being used as part of the desktop. On Windows 95/NT the count is always 1. 22 | public int MonitorCount() 23 | { 24 | return ahkReturnInt("SysGet, OutputVar, MonitorCount"); 25 | } 26 | 27 | /// Retrieves the number of the primary monitor, which will be 1 in a single-monitor system. On Windows 95/NT the primary monitor is always 1. 28 | public int MonitorPrimary() 29 | { 30 | return ahkReturnInt("SysGet, OutputVar, MonitorPrimary"); 31 | } 32 | 33 | /// Retrieves the bounding coordinates of monitor number N (if MonitorNumber is omitted, the primary monitor is used). The information is stored in four variables whose names all start with OutputVar. If N is too high or there is a problem retrieving the info, the variables are all made blank. . 34 | /// If Omitted, the primary monitor is used 35 | public string SysGet_Monitor(string MonitorNumber = "1") 36 | { 37 | string AHKLine = "SysGet, OutputVar, Monitor, " + MonitorNumber; // ahk line to execute 38 | ErrorLog_Setup(false); // ErrorLevel Detection Disabled for this function in AHK 39 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 40 | 41 | string MonLeft = GetVar("OutputVarLeft"); 42 | string MonRight = GetVar("OutputVarRight"); 43 | string MonTop = GetVar("OutputVarTop"); 44 | string MonBottom = GetVar("OutputVarBottom"); 45 | 46 | return OutVar; 47 | } 48 | 49 | /// Retrieves the bounding coordinates of monitor number N (if N is omitted, the primary monitor is used). The information is stored in four variables whose names all start with OutputVar. If N is too high or there is a problem retrieving the info, the variables are all made blank. . 50 | /// If Omitted, the primary monitor is used 51 | public string SysGet_MonitorName(string MonitorNumber = "1") 52 | { 53 | string AHKLine = "SysGet, OutputVar, MonitorName, " + MonitorNumber; // ahk line to execute 54 | ErrorLog_Setup(false); // ErrorLevel Detection Disabled for this function in AHK 55 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 56 | return OutVar; 57 | } 58 | 59 | 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /_sharpAHK/_Objects.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Drawing; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace sharpAHK 9 | { 10 | //#region === OBJECTS === 11 | 12 | 13 | public class StudentName 14 | { 15 | // The default constructor has no parameters. The default constructor 16 | // is invoked in the processing of object initializers. 17 | public StudentName() { } 18 | 19 | // The following constructor has parameters for two of the three 20 | // properties. 21 | public StudentName(string first, string last) 22 | { 23 | FirstName = first; 24 | LastName = last; 25 | } 26 | 27 | // Properties. 28 | public string FirstName { get; set; } 29 | public string LastName { get; set; } 30 | public int ID { get; set; } 31 | 32 | public override string ToString() 33 | { 34 | return FirstName + " " + ID; 35 | } 36 | } 37 | 38 | /// Stores Global Variables / Session Info / Error Level / Logging Values 39 | public static class ahkGlobal 40 | { 41 | public static List LoadedAHK { get; set; } // list of ahk files loaded from disk (file paths) 42 | 43 | public static AutoHotkey.Interop.AutoHotkeyEngine ahkdll { get; set; } // stores current AHK session 44 | 45 | public static bool ErrorLevel { get; set; } // true if error level detected in ahk command 46 | public static bool ErrorLevelEnabled { get; set; } // true if error level information is available for this command 47 | public static string ErrorLevelValue { get; set; } // ErrorLevel variable value returned from AHK session 48 | public static string ErrorLevelMsg { get; set; } // assembled error level message to display 49 | public static string ErrorLevelCustom { get; set; } // custom error level text for a command 50 | 51 | public static string LastOutputVarName { get; set; } // name of last AHK variable returned/set in AHK session 52 | public static string LastOutputVarValue { get; set; } // value returned from OutputVar in AHK session 53 | public static string LastLine { get; set; } // last line executed by AHK execute function 54 | public static string LastAction { get; set; } // last function/ahk command used by ahk execute function 55 | 56 | public static string cSharpCmd { get; set; } // sharpAHK command to recreate / log function 57 | 58 | public static bool Debug { get; set; } // 59 | 60 | public static List sharpAHKcmdHist { get; set; } // command + variables in c# format - logging ability for playback 61 | public static List ErrorLogHist { get; set; } // command + variables in c# format - logging ability for playback 62 | 63 | 64 | public static bool GlobalDebugEnabled { get; set; } // Display Debug/Diagnostic Values while Executing 65 | public static bool ErrorLevelOnGui { get; set; } // option to display error level details on gui in real time 66 | //public Control ErrorLevelDisp = new Control(); // control that displays .Text 67 | 68 | 69 | 70 | public static bool MacroPlaying { get; set; } 71 | } 72 | 73 | public class ErrorLogEntry 74 | { 75 | public bool ErrorLevel { get; set; } // true if error level detected in ahk command 76 | public bool ErrorLevelEnabled { get; set; } // true if error level information is available for this command 77 | public string ErrorLevelValue { get; set; } // ErrorLevel variable value returned from AHK session 78 | public string ErrorLevelMsg { get; set; } // assembled error level message to display 79 | public string ErrorLevelCustom { get; set; } // custom error level text for a command 80 | 81 | public string LastOutputVarName { get; set; } // name of last AHK variable returned/set in AHK session 82 | public string LastOutputVarValue { get; set; } // value returned from OutputVar in AHK session 83 | public string LastLine { get; set; } // last line executed by AHK execute function 84 | public string LastAction { get; set; } // last function/ahk command used by ahk execute function 85 | 86 | public string cSharpCmd { get; set; } // sharpAHK command to recreate / log function 87 | } 88 | 89 | /// Stores Mouse Coordinates (Relative to Screen or Window) and Info Gathered Under Mouse 90 | public class mousePos 91 | { 92 | // ex: 93 | // mousePos mp = ahk.MouseGetPos("3"); // populate object with values 94 | 95 | public int X_Window { get; set; } // stores x mouse coordinate relative to the active window 96 | public int X_Screen { get; set; } // stores y mouse coordinate relative to the screen 97 | 98 | public int Y_Window { get; set; } // stores x mouse coordinate relative to the active window 99 | public int Y_Screen { get; set; } // stores y mouse coordinate relative to the screen 100 | 101 | 102 | public string WinHwnd { get; set; } 103 | public string ControlClassNN { get; set; } 104 | public string ControlHwnd { get; set; } 105 | } 106 | 107 | /// Stores Window Coordinates and Additional Details Returned from AHK Functions 108 | public class winInfo 109 | { 110 | // ex: 111 | // winInfo win = new winInfo(); // define object reference 112 | /* 113 | public string WinTitle { get; set; } 114 | public string WinText { get; set; } 115 | public string Hwnd { get; set; } 116 | public string Class { get; set; } 117 | public string PID { get; set; } 118 | public string ProcessName { get; set; } 119 | 120 | public string Count { get; set; } 121 | 122 | public int WinX { get; set; } 123 | public int WinY { get; set; } 124 | public int WinW { get; set; } 125 | public int WinH { get; set; } 126 | */ 127 | 128 | public string WinTitle { get; set; } 129 | public string WinText { get; set; } 130 | public string WinID { get; set; } 131 | public string Class { get; set; } 132 | public string MinMax { get; set; } 133 | public bool IsMin { get; set; } 134 | public bool IsMax { get; set; } 135 | public string Count { get; set; } 136 | 137 | public int WinX { get; set; } 138 | public int WinY { get; set; } 139 | public int WinW { get; set; } 140 | public int WinH { get; set; } 141 | 142 | 143 | public Image WinScreenShot 144 | { 145 | get 146 | { 147 | //return this.name; 148 | return null; 149 | } 150 | set 151 | { 152 | //this.name = value; 153 | } 154 | } 155 | 156 | public Image WinIcon { get; set; } 157 | 158 | public string PID { get; set; } 159 | public string ProcessName { get; set; } 160 | 161 | 162 | } 163 | 164 | 165 | // #region === v1 Objects === 166 | 167 | /// 168 | /// used to return window position 169 | /// 170 | public struct Rect 171 | { 172 | public int Left { get; set; } 173 | public int Top { get; set; } 174 | public int Right { get; set; } 175 | public int Bottom { get; set; } 176 | 177 | public int Width { get; set; } 178 | public int Height { get; set; } 179 | } 180 | 181 | /// 182 | /// used to return window position 183 | /// 184 | public struct Coordinates 185 | { 186 | public int XPos { get; set; } 187 | public int YPos { get; set; } 188 | 189 | } 190 | 191 | /// 192 | /// control info parameters 193 | /// 194 | public struct conInfo 195 | { 196 | public string ControlName { get; set; } 197 | public string ControlText { get; set; } 198 | public IntPtr ControlHwnd { get; set; } 199 | public string ControlClass { get; set; } 200 | public string ControlValue { get; set; } 201 | 202 | public int ControlX { get; set; } 203 | public int ControlY { get; set; } 204 | public int ControlW { get; set; } 205 | public int ControlH { get; set; } 206 | 207 | public bool ControlChecked { get; set; } 208 | public bool ControlEnabled { get; set; } 209 | public bool ControlVisible { get; set; } 210 | } 211 | 212 | /// 213 | /// window / mouse / control info parameters 214 | /// 215 | public struct wInfo 216 | { 217 | public int MouseXPos { get; set; } 218 | public int MouseYPos { get; set; } 219 | 220 | public string WinTitle { get; set; } 221 | public IntPtr WinHwnd { get; set; } 222 | public string WinClass { get; set; } 223 | public string WinPID { get; set; } 224 | public string WinText { get; set; } 225 | 226 | public int WinX { get; set; } 227 | public int WinY { get; set; } 228 | public int WinW { get; set; } 229 | public int WinH { get; set; } 230 | 231 | public IntPtr ControlHwnd { get; set; } 232 | 233 | } 234 | 235 | 236 | 237 | } 238 | -------------------------------------------------------------------------------- /_sharpAHK/_Processes.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Diagnostics; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace sharpAHK 9 | { 10 | public partial class _AHK 11 | { 12 | #region === Process Management === 13 | 14 | /// Performs one of the following operations on a process: checks if it exists; changes its priority; closes it; waits for it to close. 15 | /// Exist | Close | List | Priority | Wait | WaitClose 16 | /// This parameter can be either a number (the PID) or a process name as described below. It can also be left blank to change the priority of the script itself. 17 | /// See AHK Documentation For Options 18 | public bool process(string Cmd, string PIDorName, string Param3 = "") 19 | { 20 | string AHKLine = "Process, " + Cmd + "," + PIDorName + "," + Param3; // ahk line to execute 21 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 22 | Execute(AHKLine); // execute AHK code and return variable value 23 | 24 | if (!ahkGlobal.ErrorLevel) { return true; } // no error level - return true for success 25 | return false; // error level detected - success = false 26 | } 27 | 28 | /// Runs an external program. 29 | /// A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), or system verb to launch (see remarks). If Target is a local file and no path was specified with it, A_WorkingDir will be searched first. If no matching file is found there, the system will search for and launch the file if it is integrated ("known"), e.g. by being contained in one of the PATH folders. To pass parameters, add them immediately after the program or document name. If a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases). 30 | /// The working directory for the launched item. Do not enclose the name in double quotes even if it contains spaces. If omitted, the script's own working directory (A_WorkingDir) will be used. 31 | /// Max: launch maximized | Min: launch minimized | Hide: launch hidden | UseErrorLevel: If the launch fails, this option skips the warning dialog, sets ErrorLevel to the word ERROR, and allows the current thread to continue. 32 | /// Returns OutputVarPID as string 33 | public string Run(string Target, string WorkingDir = "", string MinMaxHideUseErrorLevel = "") 34 | { 35 | if (Target == null) { return ""; } 36 | 37 | string target = Target.Replace(",", "`,"); 38 | string workingDir = WorkingDir.Replace(",", "`,"); 39 | 40 | string AHKLine = "Run, " + target + "," + workingDir + "," + MinMaxHideUseErrorLevel + ", OutputVarPID"; // ahk line to execute 41 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 42 | string OutVar = Execute(AHKLine, "OutputVarPID"); // execute AHK code and return variable value 43 | return OutVar; 44 | 45 | // v1 ToDo 46 | /* 47 | public IntPtr _Run(string Target, string Arguments = "", bool Hidden = false) // run application path. includes win tools (Notepad, cmd, calc, word, paint, regedit, notepad++ as TARGET to launch) 48 | { 49 | IntPtr ApphWnd = new IntPtr(0); 50 | 51 | if (Target.ToUpper() == "NOTEPAD") { Target = Environment.SystemDirectory + "\\notepad.exe"; } 52 | if (Target.ToUpper() == "CMD" || Target.ToUpper() == "COMMAND") { Target = Environment.SystemDirectory + "\\cmd.exe"; } 53 | if (Target.ToUpper() == "CALC" || Target.ToUpper() == "CALCULATOR") { Target = Environment.SystemDirectory + "\\calc.exe"; } 54 | if (Target.ToUpper() == "WORD") { Target = Environment.SystemDirectory + "\\word.exe"; } 55 | if (Target.ToUpper() == "PAINT") { Target = Environment.SystemDirectory + "\\paint.exe"; } 56 | if (Target.ToUpper() == "REGEDIT") { Target = Environment.SystemDirectory + "\\regedit.exe"; } 57 | 58 | if (Target.ToUpper() == "NOTEPAD++") 59 | { 60 | Target = @"C:\Google Drive\AHK\Lib\Tool_Library\Office\Notepad++\App\Notepad++\Notepad++.exe"; 61 | if (!File.Exists(Target)) { Target = @"C:\Users\jason\Google Drive\AHK\Lib\Tool_Library\Office\Notepad++\App\Notepad++\Notepad++.exe"; } 62 | } 63 | 64 | if (Target.ToUpper().Contains("HTTP://")) //user trying to open url 65 | { 66 | Process proc; 67 | proc = System.Diagnostics.Process.Start(Target); 68 | proc.WaitForInputIdle(); 69 | try { ApphWnd = proc.MainWindowHandle; } 70 | catch { } 71 | return ApphWnd; 72 | } 73 | 74 | if (File.Exists(Target)) 75 | { 76 | FileInfo info = new FileInfo(Target); 77 | 78 | // check to see if target is a directory, if so 79 | FileAttributes attr = File.GetAttributes(Target); 80 | if ((attr & FileAttributes.Directory) == FileAttributes.Directory) 81 | { 82 | //it's a directory 83 | OpenDir(Target); 84 | return ApphWnd; 85 | } 86 | 87 | 88 | ProcessStartInfo startInfo = new ProcessStartInfo(); 89 | startInfo.WorkingDirectory = info.Directory.ToString(); 90 | startInfo.FileName = Target; 91 | startInfo.Arguments = Arguments; 92 | 93 | if (Hidden == true) 94 | { 95 | startInfo.WindowStyle = ProcessWindowStyle.Hidden; 96 | } 97 | 98 | Process proc; 99 | proc = Process.Start(startInfo); 100 | try { proc.WaitForInputIdle(); } 101 | catch { } 102 | 103 | try { ApphWnd = proc.MainWindowHandle; } 104 | catch { } 105 | return ApphWnd; 106 | } 107 | 108 | return ApphWnd; 109 | } 110 | */ 111 | 112 | 113 | } 114 | 115 | /// Runs an external program. RunWait will wait until the program finishes before continuing. 116 | /// A document, URL, executable file (.exe, .com, .bat, etc.), shortcut (.lnk), or system verb to launch (see remarks). If Target is a local file and no path was specified with it, A_WorkingDir will be searched first. If no matching file is found there, the system will search for and launch the file if it is integrated ("known"), e.g. by being contained in one of the PATH folders. To pass parameters, add them immediately after the program or document name. If a parameter contains spaces, it is safest to enclose it in double quotes (even though it may work without them in some cases). 117 | /// The working directory for the launched item. Do not enclose the name in double quotes even if it contains spaces. If omitted, the script's own working directory (A_WorkingDir) will be used. 118 | /// Max: launch maximized | Min: launch minimized | Hide: launch hidden | UseErrorLevel: If the launch fails, this option skips the warning dialog, sets ErrorLevel to the word ERROR, and allows the current thread to continue. 119 | /// Returns OutputVarPID as string 120 | public string RunWait(string Target, string WorkingDir = "", string MinMaxHideUseErrorLevel = "") 121 | { 122 | string target = Target.Replace(",", "`,"); 123 | string workingDir = WorkingDir.Replace(",", "`,"); 124 | 125 | string AHKLine = "RunWait, " + target + "," + workingDir + "," + MinMaxHideUseErrorLevel + ", OutputVarPID"; // ahk line to execute 126 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 127 | string OutVar = Execute(AHKLine, "OutputVarPID"); // execute AHK code and return variable value 128 | 129 | // returns OutputVarPID 130 | return OutVar; 131 | 132 | // v1 ToDo 133 | /* 134 | public bool _RunWait(string ProcessPath, string Arguments = "", bool Hidden = false) // runs application and waits for the application to end before continuing 135 | { 136 | if (File.Exists(ProcessPath)) 137 | { 138 | Process process = new Process(); 139 | process.StartInfo.FileName = ProcessPath; 140 | process.StartInfo.Arguments = Arguments; 141 | process.StartInfo.ErrorDialog = true; 142 | //process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized; 143 | if (Hidden == true) 144 | { 145 | process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 146 | } 147 | process.Start(); 148 | process.WaitForExit(); 149 | return true; 150 | } 151 | 152 | return false; 153 | } 154 | */ 155 | 156 | } 157 | 158 | /// Specifies a set of user credentials to use for all subsequent uses of Run and RunWait. Requires Windows 2000/XP or later. 159 | /// If this and the other parameters are all omitted, the RunAs feature will be turned off, which restores Run and RunWait to their default behavior. Otherwise, this is the username under which new processes will be created. 160 | /// User's password. 161 | /// User's domain. To use a local account, leave this blank. If that fails to work, try using @YourComputerName. 162 | public void RunAs(string User = "", string Password = "", string Domain = "") 163 | { 164 | ErrorLog_Setup(false); 165 | Execute("RunAs, " + User + "," + Password + "," + Domain); 166 | } 167 | 168 | /// Shuts down, restarts, or logs off the system. 169 | /// A combination of shutdown codes: LogOff = 0 | ShutDown = 1 | Reboot = 2 | Force = 4 | Power Down = 8 170 | public void Shutdown(string Code) 171 | { 172 | ErrorLog_Setup(false); 173 | Execute("Shutdown, " + Code); 174 | } 175 | 176 | /// 177 | /// Returns exe path of window by WinTitle or WinHandle 178 | /// 179 | /// 180 | /// 181 | public string ProcessPath(object WinTitle) 182 | { 183 | IntPtr hWnd = WinHwnd(WinTitle); //returns Window Handle (from either handle or window title) 184 | 185 | uint pid = 0; 186 | _GetWindowThreadProcessId(hWnd, out pid); 187 | if (hWnd != IntPtr.Zero) 188 | { 189 | if (pid != 0) 190 | { 191 | var process = Process.GetProcessById((int)pid); 192 | if (process != null) 193 | { 194 | return process.MainModule.FileName.ToString(); 195 | } 196 | } 197 | } 198 | return ""; 199 | } 200 | 201 | 202 | #endregion 203 | 204 | 205 | /// 206 | /// Either Activate or Launch Application 207 | /// 208 | /// WinTitle to Activate / Look For 209 | /// Application Path to Launch 210 | public void RunOrActivate(string WinTitle, string Path) 211 | { 212 | if (WinExist(WinTitle)) { WinRestore(WinTitle); WinActivate(WinTitle); } else { Run(Path); } 213 | } 214 | 215 | 216 | } 217 | } 218 | -------------------------------------------------------------------------------- /_sharpAHK/_Registry.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace sharpAHK 8 | { 9 | public partial class _AHK 10 | { 11 | #region === Registry === 12 | 13 | /// Deletes a subkey or value from the registry. 14 | /// Must be either HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, or HKEY_CURRENT_CONFIG (or the abbreviations for each of these, such as HKLM). To access a remote registry, prepend the computer name and a colon, as in this example: \\workstation01:HKEY_LOCAL_MACHINE 15 | /// The name of the subkey (e.g. Software\SomeApplication). 16 | /// The name of the value to delete. If omitted, the entire SubKey will be deleted. To delete Subkey's default value -- which is the value displayed as "(Default)" by RegEdit -- use the phrase AHK_DEFAULT for this parameter. 17 | /// Returns True if No ErrorLevel 18 | public bool RegDelete(string RootKey, string SubKey, string ValueName = "") 19 | { 20 | ErrorLog_Setup(true); 21 | Execute("RegDelete, " + RootKey + "," + SubKey + "," + ValueName); 22 | 23 | if (!ahkGlobal.ErrorLevel) { return true; } // no error level - return true for success 24 | return false; // error level detected - success = false 25 | } 26 | 27 | /// Reads a value from the registry. 28 | /// Must be either HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, or HKEY_CURRENT_CONFIG (or the abbreviations for each of these, such as HKLM). To access a remote registry, prepend the computer name and a colon, as in this example: \\workstation01:HKEY_LOCAL_MACHINE 29 | /// The name of the subkey (e.g. Software\SomeApplication). 30 | /// The name of the value to retrieve. If omitted, Subkey's default value will be retrieved, which is the value displayed as "(Default)" by RegEdit. If there is no default value (that is, if RegEdit displays "value not set"), OutputVar is made blank and ErrorLevel is set to 1. 31 | public string RegRead(string RootKey, string SubKey, string ValueName = "") 32 | { 33 | string AHKLine = "RegRead, OutputVar, " + RootKey + "," + SubKey + "," + ValueName; // ahk line to execute 34 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 35 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 36 | return OutVar; 37 | } 38 | 39 | /// Writes a value to the registry. 40 | /// Must be either REG_SZ, REG_EXPAND_SZ, REG_MULTI_SZ, REG_DWORD, or REG_BINARY. 41 | /// Must be either HKEY_LOCAL_MACHINE, HKEY_USERS, HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, or HKEY_CURRENT_CONFIG (or the abbreviations for each of these, such as HKLM). To access a remote registry, prepend the computer name and a colon, as in this example: \\workstation01:HKEY_LOCAL_MACHINE 42 | /// The name of the subkey (e.g. Software\SomeApplication). If SubKey does not exist, it is created (along with its ancestors, if necessary). If SubKey is left blank, the value is written directly into RootKey (though some operating systems might refuse to write in HKEY_CURRENT_USER's top level). 43 | /// The name of the value that will be written to. If blank or omitted, Subkey's default value will be used, which is the value displayed as "(Default)" by RegEdit. 44 | /// The value to be written. If omitted, it will default to an empty (blank) string, or 0, depending on ValueType. If the text is long, it can be broken up into several shorter lines by means of a continuation section, which might improve readability and maintainability. 45 | /// Returns True if No ErrorLevel 46 | public bool RegWrite(string ValueType, string RootKey, string SubKey, string ValueName = "", string Value = "") 47 | { 48 | string AHKLine = "RegWrite, " + ValueType + "," + RootKey + "," + SubKey + "," + ValueName + "," + Value; // ahk line to execute 49 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 50 | Execute(AHKLine); // execute AHK code and return variable value 51 | 52 | if (!ahkGlobal.ErrorLevel) { return true; } // no error level - return true for success 53 | return false; // error level detected - success = false 54 | } 55 | 56 | 57 | #endregion 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /_sharpAHK/_Sound.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace sharpAHK 8 | { 9 | public partial class _AHK 10 | { 11 | #region === Sound Commands === 12 | 13 | /// Emits a tone from the PC speaker. 14 | /// The frequency of the sound, which can be an expression. It should be a number between 37 and 32767. If omitted, the frequency will be 523. 15 | /// The duration of the sound, in milliseconds (can be an expression). If omitted, the duration will be 150. 16 | public void SoundBeep(object Frequency = null, object Duration = null) 17 | { 18 | string frequencey = ""; string duration = ""; 19 | if (Frequency != null) { frequencey = Frequency.ToString(); } 20 | if (Duration != null) { duration = Duration.ToString(); } 21 | 22 | ErrorLog_Setup(false); 23 | Execute("SoundBeep, " + frequencey + "," + duration); 24 | } 25 | 26 | /// Retrieves various settings from a sound device (master mute, master volume, etc.) 27 | /// If omitted or blank, it defaults to the word MASTER. Otherwise, it can be one of the following words: MASTER (synonymous with SPEAKERS), DIGITAL, LINE, MICROPHONE, SYNTH, CD, TELEPHONE, PCSPEAKER, WAVE, AUX, ANALOG, HEADPHONES, or N/A. If the sound device lacks the specified ComponentType, ErrorLevel will indicate the problem. The component labled Auxiliary in some mixers might be accessible as ANALOG rather than AUX. If a device has more than one instance of ComponentType (two of type LINE, for example), usually the first contains the playback settings and the second contains the recording settings. To access an instance other than the first, append a colon and a number to this parameter. For example: Analog:2 is the second instance of the analog component. 28 | /// If omitted or blank, it defaults to VOLUME. Otherwise, it can be one of the following words: VOLUME (or VOL), ONOFF, MUTE, MONO, LOUDNESS, STEREOENH, BASSBOOST, PAN, QSOUNDPAN, BASS, TREBLE, EQUALIZER, or the number of a valid control type (see soundcard analysis script). If the specified ComponentType lacks the specified ControlType, ErrorLevel will indicate the problem. 29 | /// If this parameter is omitted, it defaults to 1 (the first sound device), which is usually the system's default device for recording and playback. Specify a number higher than 1 to operate upon a different sound device. This parameter can be an expression. 30 | public string SoundGet(string ComponentType = "", string ControlType = "", string DeviceNumber = "") 31 | { 32 | string AHKLine = "SoundGet, OutputVar, " + ComponentType + "," + ControlType + "," + DeviceNumber; // ahk line to execute 33 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 34 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 35 | return OutVar; 36 | } 37 | 38 | /// Retrieves the wave output volume for a sound device. 39 | /// If this parameter is omitted, it defaults to 1 (the first sound device), which is usually the system's default device for recording and playback. Specify a number higher than 1 to operate upon a different sound device. 40 | public string SoundGetWaveVolume(string DeviceNumber = "") 41 | { 42 | string AHKLine = "SoundGetWaveVolume, OutputVar, " + DeviceNumber; // ahk line to execute 43 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 44 | string OutVar = Execute(AHKLine, "OutputVar"); // execute AHK code and return variable value 45 | return OutVar; 46 | } 47 | 48 | /// Plays a sound, video, or other supported file type. 49 | /// The name of the file to be played, which is assumed to be in %A_WorkingDir% if an absolute path isn't specified. To produce standard system sounds, specify an asterisk followed by a number as shown below. Note: the wait parameter has no effect in this mode. *-1: Simple beep. If the sound card is not available, the sound is generated using the speaker. *16: Hand (stop/error) *32: Question *48: Exclamation *64: Asterisk (info) 50 | /// If False, the script's current thread will move on to the next commmand(s) while the file is playing. To avoid this, set Wait to TRUE, which causes the current thread to wait until the file is finished playing before continuing. Even while waiting, new threads can be launched via hotkey, custom menu item, or timer. Known limitation: If the WAIT parameter is omitted, the OS might consider the playing file to be "in use" until the script closes or until another file is played (even a nonexistent file). 51 | public void SoundPlay(string Filename, bool WaitUntilFinished = false) 52 | { 53 | string wait = ""; 54 | if (WaitUntilFinished) { wait = "Wait"; } 55 | 56 | ErrorLog_Setup(false); 57 | Execute("SoundPlay, " + Filename + "," + wait); 58 | } 59 | 60 | /// Changes various settings of a sound device (master mute, master volume, etc.) 61 | /// Percentage number between -100 and 100 inclusive (it can be a floating point number or expression). If the number begins with a plus or minus sign, the current setting will be adjusted up or down by the indicated amount. Otherwise, the setting will be set explicitly to the level indicated by NewSetting. For ControlTypes with only two possible settings -- namely ONOFF, MUTE, MONO, LOUDNESS, STEREOENH, and BASSBOOST -- any positive number will turn on the setting and a zero will turn it off. However, if the number begins with a plus or minus sign, the setting will be toggled (set to the opposite of its current state). 62 | /// If omitted or blank, it defaults to the word MASTER. Otherwise, it can be one of the following words: MASTER (synonymous with SPEAKERS), DIGITAL, LINE, MICROPHONE, SYNTH, CD, TELEPHONE, PCSPEAKER, WAVE, AUX, ANALOG, HEADPHONES, or N/A. If the sound device lacks the specified ComponentType, ErrorLevel will indicate the problem. The component labeled Auxiliary in some mixers might be accessible as ANALOG rather than AUX. If a device has more than one instance of ComponentType (two of type LINE, for example), usually the first contains the playback settings and the second contains the recording settings. To access an instance other than the first, append a colon and a number to this parameter. For example: Analog:2 is the second instance of the analog component. 63 | /// If omitted or blank, it defaults to VOLUME. Otherwise, it can be one of the following words: VOLUME (or VOL), ONOFF, MUTE, MONO, LOUDNESS, STEREOENH, BASSBOOST, PAN, QSOUNDPAN, BASS, TREBLE, EQUALIZER, or the number of a valid control type (see soundcard analysis script). If the specified ComponentType lacks the specified ControlType, ErrorLevel will indicate the problem. 64 | /// If this parameter is omitted, it defaults to 1 (the first sound device), which is usually the system's default device for recording and playback. Specify a number higher than 1 to operate upon a different sound device. This parameter can be an expression. 65 | public bool SoundSet(string NewSetting, string ComponentType = "", string ControlType = "", string DeviceNumber = "") 66 | { 67 | string AHKLine = "SoundSet, " + NewSetting + "," + ComponentType + "," + ControlType + "," + DeviceNumber; // ahk line to execute 68 | ErrorLog_Setup(true); // ErrorLevel Detection Enabled for this function in AHK 69 | Execute(AHKLine); // execute AHK code and return variable value 70 | 71 | if (!ahkGlobal.ErrorLevel) { return true; } // no error level - return true for success 72 | return false; // error level detected - success = false 73 | } 74 | 75 | /// Changes the wave output volume for a sound device. 76 | /// Percentage number between -100 and 100 inclusive (it can be a floating point number or an expression). If the number begins with a plus or minus sign, the current volume level will be adjusted up or down by the indicated amount. Otherwise, the volume will be set explicitly to the level indicated by Percent. 77 | /// If this parameter is omitted, it defaults to 1 (the first sound device), which is usually the system's default device for recording and playback. Specify a number higher than 1 to operate upon a different sound device. 78 | public void SoundSetWaveVolume(string Percent, string DeviceNumber = "") 79 | { 80 | ErrorLog_Setup(false); 81 | Execute("SoundSetWaveVolume, " + Percent + "," + DeviceNumber); 82 | } 83 | 84 | 85 | #endregion 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /_sharpAHK/_User32.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Runtime.InteropServices; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace sharpAHK 9 | { 10 | public partial class _AHK 11 | { 12 | // === User32 DLL Calls === 13 | 14 | 15 | // User32.dll (used in AHK Functions) 16 | 17 | [DllImport("User32")] 18 | private static extern int _ShowWindow(int hwnd, int nCmdShow); // user32.dll call 19 | 20 | private const int SW_HIDE = 0; // user32.dll var 21 | private const int SW_SHOW = 5; // user32.dll var 22 | 23 | [DllImport("user32.dll")] 24 | private static extern bool _SetForegroundWindow(IntPtr hWnd); // user32.dll call - win activate 25 | 26 | [DllImport("user32.dll")] 27 | private static extern bool _ShowWindowAsync(IntPtr hWnd, int nCmdShow); // user32.dll call - win restore 28 | 29 | [DllImport("user32.dll")] 30 | static extern IntPtr GetForegroundWindow(); // user32.dll call - Active Window Title 31 | //static extern IntPtr _GetForegroundWindow(); // user32.dll call - Active Window Title 32 | 33 | [DllImport("user32.dll")] 34 | static extern int _GetWindowText(IntPtr hWnd, StringBuilder text, int count); // user32.dll call - Active Window Title 35 | 36 | [DllImport("user32.dll")] 37 | [return: MarshalAs(UnmanagedType.Bool)] 38 | static extern bool _GetWindowPlacement(IntPtr hWnd, ref WINDOWPLACEMENT lpwndpl); // user32.dll call - is WinMaximized / WinMinimized 39 | 40 | private struct WINDOWPLACEMENT 41 | { 42 | public int length; 43 | public int flags; 44 | public int showCmd; 45 | public System.Drawing.Point ptMinPosition; 46 | public System.Drawing.Point ptMaxPosition; 47 | public System.Drawing.Rectangle rcNormalPosition; 48 | } 49 | 50 | //=== Set Window Always On Top ============ 51 | private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1); // user32.dll call 52 | private static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2); // user32.dll call 53 | private const UInt32 SWP_NOSIZE = 0x0001; // user32.dll call 54 | private const UInt32 SWP_NOMOVE = 0x0002; // user32.dll call 55 | private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE; // user32.dll call 56 | 57 | static readonly IntPtr HWND_TOP = new IntPtr(0); // user32.dll call 58 | static readonly IntPtr HWND_BOTTOM = new IntPtr(1); // user32.dll call 59 | 60 | [DllImport("user32.dll")] 61 | [return: MarshalAs(UnmanagedType.Bool)] // changed to private - confirm working 62 | private static extern bool _SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); // user32.dll call 63 | 64 | [DllImport("user32.dll", EntryPoint = "SetWindowPos")] // changed to private - confirm working 65 | private static extern IntPtr _SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags); // user32.dll call - Win Move 66 | 67 | 68 | [DllImport("user32.dll", CharSet = CharSet.Auto)] 69 | static extern IntPtr _SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam); // user32.dll call 70 | 71 | const UInt32 WM_CLOSE = 0x0010; //win close 72 | 73 | //===== Get Window Position ======= 74 | [DllImport("user32.dll", CharSet = CharSet.Auto)] // changed to private - confirm working 75 | private static extern IntPtr _FindWindow(string strClassName, string strWindowName); // user32.dll call 76 | 77 | [DllImport("user32.dll")] // changed to private - confirm working 78 | private static extern bool _GetWindowRect(IntPtr hwnd, ref Rect rectangle); // user32.dll call 79 | 80 | //[DllImport("user32.dll", CharSet = CharSet.Auto)] 81 | //private static extern int GetWindowText(int hWnd, StringBuilder title, int size); // user32.dll call - Get Window Title 82 | 83 | [DllImport("User32.dll", CharSet = CharSet.Auto)] 84 | static extern long GetWindowText(IntPtr hwnd, StringBuilder lpString, int cch); 85 | 86 | 87 | private delegate bool EnumWindowsProc(IntPtr hWnd, int lParam); // user32.dll call 88 | 89 | [DllImport("USER32.DLL")] 90 | private static extern bool _EnumWindows(EnumWindowsProc enumFunc, int lParam); // user32.dll call 91 | 92 | [DllImport("USER32.DLL")] 93 | private static extern int _GetWindowTextLength(IntPtr hWnd); // user32.dll call 94 | 95 | [DllImport("USER32.DLL")] 96 | private static extern bool _IsWindowVisible(IntPtr hWnd); // user32.dll call 97 | 98 | [DllImport("USER32.DLL")] 99 | private static extern IntPtr _GetShellWindow(); // user32.dll call 100 | 101 | //WARN: Only for "Any CPU": 102 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] 103 | private static extern int _GetWindowThreadProcessId(IntPtr handle, out uint processId); // user32.dll call 104 | 105 | 106 | //=== post message ==== 107 | [DllImport("user32.dll")] 108 | [return: MarshalAs(UnmanagedType.Bool)] 109 | static extern bool _PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); // user32.dll call 110 | 111 | 112 | const uint WM_KEYDOWN = 0x0100; 113 | const uint WM_KEYUP = 0x0101; 114 | const uint WM_CHAR = 0x0102; 115 | const int VK_TAB = 0x09; 116 | const int VK_ENTER = 0x0D; 117 | const int VK_UP = 0x26; 118 | const int VK_DOWN = 0x28; 119 | const int VK_RIGHT = 0x27; 120 | 121 | const uint NpadMsg = 0x111; 122 | //const IntPtr wParam = 44010; 123 | 124 | 125 | [DllImport("user32.dll")] 126 | static extern int _GetFocus(); // user32.dll call 127 | 128 | [DllImport("user32.dll")] 129 | static extern bool _AttachThreadInput(uint idAttach, uint idAttachTo, bool fAttach); // user32.dll call 130 | 131 | [DllImport("kernel32.dll")] 132 | static extern uint _GetCurrentThreadId(); // user32.dll call 133 | 134 | [DllImport("user32.dll")] 135 | static extern uint _GetWindowThreadProcessId(int hWnd, int ProcessId); // user32.dll call 136 | 137 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)] 138 | static extern int _SendMessage(int hWnd, int Msg, int wParam, StringBuilder lParam); // user32.dll call 139 | 140 | const int WM_SETTEXT = 12; 141 | //const int WM_GETTEXT = 13; 142 | 143 | [DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)] 144 | static extern int _GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount); // user32.dll call 145 | 146 | 147 | private const int WM_SYSCOMMAND = 274; 148 | private const int SC_MAXIMIZE = 61488; 149 | 150 | // changed to private - confirm working 151 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] 152 | private static extern int _SetParent(IntPtr hWndChild, IntPtr hWndNewParent); // user32.dll call 153 | 154 | // changed to private - confirm working 155 | [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true, ExactSpelling = true)] 156 | private static extern int _SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); // user32.dll call 157 | 158 | 159 | //======= Mouse Click ====================== 160 | [System.Runtime.InteropServices.DllImport("user32.dll")] 161 | static extern bool _SetCursorPos(int x, int y); // user32.dll call 162 | 163 | // changed to private - confirm working 164 | [System.Runtime.InteropServices.DllImport("user32.dll")] 165 | private static extern void mouse_event(int dwFlags, int dx, int dy, int cButtons, int dwExtraInfo); // user32.dll call 166 | 167 | private const int MOUSEEVENTF_MOVE = 0x0001; /* mouse move */ 168 | private const int MOUSEEVENTF_RIGHTDOWN = 0x0008; /* right button down */ 169 | private const int MOUSEEVENTF_RIGHTUP = 0x0010; /* right button up */ 170 | private const int MOUSEEVENTF_LEFTDOWN = 0x02; // changed to private - confirm working 171 | private const int MOUSEEVENTF_LEFTUP = 0x04; // changed to private - confirm working 172 | 173 | 174 | const int WM_GETTEXT = 0x000D; 175 | const int WM_GETTEXTLENGTH = 0x000E; 176 | 177 | // changed to private - confirm working 178 | [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true, CharSet = System.Runtime.InteropServices.CharSet.Auto)] 179 | private static extern int _RegisterWindowMessage(string lpString); // user32.dll call 180 | 181 | // changed to private - confirm working 182 | [System.Runtime.InteropServices.DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = System.Runtime.InteropServices.CharSet.Auto)] // 183 | private static extern bool _SendMessage(IntPtr hWnd, uint Msg, int wParam, StringBuilder lParam); // user32.dll call 184 | 185 | // changed to private - confirm working 186 | [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)] 187 | private static extern IntPtr _SendMessage(int hWnd, int Msg, int wparam, int lparam); // user32.dll call 188 | 189 | // changed to private - confirm working 190 | [DllImport("User32.dll")] 191 | private static extern Boolean _EnumChildWindows(int hWndParent, Delegate lpEnumFunc, int lParam); // user32.dll call 192 | 193 | // changed to private - confirm working 194 | private void _PostMsg(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam) // send postmessage to another application/form 195 | { 196 | _PostMessage(hWnd, msg, wParam, lParam); 197 | } 198 | 199 | 200 | } 201 | } 202 | -------------------------------------------------------------------------------- /_sharpAHK/_Web.cs: -------------------------------------------------------------------------------- 1 | using AHKExpressions; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Drawing; 5 | using System.IO; 6 | using System.Linq; 7 | using System.Net; 8 | using System.Text; 9 | using System.Threading.Tasks; 10 | 11 | namespace sharpAHK 12 | { 13 | public partial class _AHK 14 | { 15 | //#region === Web === 16 | 17 | /// 18 | /// Downloads HTML string from URL path 19 | /// 20 | /// URL to Download 21 | /// Optional Local File Path to Save HTML To (Only Returns HTML as String if Blank) 22 | /// Optional Login Parameter for URL 23 | /// Optional Password Parameter for URL 24 | /// Returns HTML from Website as String 25 | /// 26 | /// string HTML = ahk.Download_HTML("http://www.imdb.com/title/tt1985949/", "c:\\HTML.txt"); 27 | /// 28 | public string Download_HTML(string URL, string SaveFile = "", string login = "", string pass = "", bool HideErrorMsg = true) 29 | { 30 | //### download a web page to a string 31 | WebClient client = new WebClient(); 32 | 33 | if (login != "") // option to set login parameters 34 | { 35 | client.Credentials = new System.Net.NetworkCredential(login, pass); 36 | } 37 | 38 | client.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)"); 39 | 40 | string s = ""; 41 | try 42 | { 43 | Stream data = client.OpenRead(URL); 44 | StreamReader reader = new StreamReader(data); 45 | s = reader.ReadToEnd(); 46 | 47 | if (SaveFile != "") 48 | { 49 | FileDelete(SaveFile); 50 | FileAppend(s, SaveFile); 51 | //Run(SaveFile); 52 | } 53 | } 54 | catch(Exception ex) 55 | { 56 | if (!HideErrorMsg) 57 | { 58 | _AHK ahk = new _AHK(); 59 | ahk.MsgBox(ex.ToString()); 60 | } 61 | return ""; 62 | } 63 | 64 | 65 | 66 | 67 | return s; 68 | } 69 | 70 | 71 | /// 72 | /// Download File From Website 73 | /// 74 | /// URL to File 75 | /// Local Save Path 76 | /// Option to Skip Downloading if Local File Already Exists 77 | /// 78 | public bool Download_File(string remoteFileUrl, string localFileName, bool SkipExisting = true) 79 | { 80 | // if enabled, will skip downloading the same file again 81 | 82 | if (SkipExisting) { if (File.Exists(localFileName)) { return true; } } 83 | 84 | 85 | WebClient webClient = new WebClient(); 86 | try 87 | { 88 | webClient.DownloadFile(remoteFileUrl, localFileName); 89 | } 90 | catch (Exception ex) 91 | { 92 | //ahk.MsgBox(ex.ToString()); 93 | return false; 94 | } 95 | 96 | // confirm file is found in local location after download, return true if found 97 | 98 | if (File.Exists(localFileName)) { return true; } 99 | else { MsgBox("Error Saving " + localFileName + " ??\n\nLocal File Not Found\n\nURL: " + remoteFileUrl); return false; } 100 | } 101 | 102 | /// 103 | /// URL to Image 104 | /// 105 | /// 106 | /// 107 | public Image Download_Image(string URL) 108 | { 109 | using (System.Net.WebClient webClient = new System.Net.WebClient()) 110 | { 111 | using (Stream stream = webClient.OpenRead(URL)) 112 | { 113 | return Image.FromStream(stream); 114 | } 115 | } 116 | } 117 | 118 | /// 119 | /// Returns Public IP Address 120 | /// 121 | /// 122 | public static string PublicIP() 123 | { 124 | string url = "http://checkip.dyndns.org"; 125 | System.Net.WebRequest req = System.Net.WebRequest.Create(url); 126 | System.Net.WebResponse resp = req.GetResponse(); 127 | System.IO.StreamReader sr = new System.IO.StreamReader(resp.GetResponseStream()); 128 | string response = sr.ReadToEnd().Trim(); 129 | string[] a = response.Split(':'); 130 | string a2 = a[1].Substring(1); 131 | string[] a3 = a2.Split('<'); 132 | string a4 = a3[0]; 133 | return a4; 134 | } 135 | 136 | 137 | /// 138 | /// Takes HTML Listing from IIS Directory Listing and Parses Out Links (works for 1 directory deep) 139 | /// 140 | /// 141 | /// 142 | public List LinkFromIISDir(string URL = "http://liveinthemedia.com/Sonarr") 143 | { 144 | List Links = new List(); 145 | 146 | string baseURL = URL; 147 | WebClient client = new WebClient(); 148 | string content = ""; 149 | 150 | try 151 | { 152 | content = client.DownloadString(baseURL); 153 | } 154 | catch (Exception ex) 155 | { 156 | MsgBox(ex.ToString()); 157 | return Links; 158 | } 159 | 160 | if (content != "") 161 | { 162 | string url = ""; 163 | List Lines = Text_ToList(content, true, true, false); 164 | foreach (string line in Lines) 165 | { 166 | if (line.Contains(" lines = StringSplit_List(html, "|", true); 178 | int i = 0; string header = ""; 179 | foreach (string line in lines) 180 | { 181 | i++; if (i < 3) { header = header + line; continue; } // skip first two header lines 182 | string tLine = StringSplit(line, ">", 0).Replace("\"", ""); 183 | 184 | string urr = bURL + tLine; 185 | Links.Add(urr); 186 | } 187 | } 188 | 189 | return Links; 190 | } 191 | 192 | } 193 | } 194 | -------------------------------------------------------------------------------- /_sharpAHK/_Windows.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace sharpAHK 8 | { 9 | public partial class _AHK 10 | { 11 | // === Windows Applications === 12 | 13 | /// 14 | /// Launch Windows Disk Manager 15 | /// 16 | public void Windows_DiskMgr() 17 | { 18 | Run("diskmgmt.msc"); 19 | } 20 | 21 | /// 22 | /// Launch Windows MyComputer Window. 23 | /// 24 | public void MyComputer() 25 | { 26 | Run("::{20d04fe0-3aea-1069-a2d8-08002b30309d}"); 27 | } 28 | 29 | /// 30 | /// Launch Windows RecycleBin Window 31 | /// 32 | public void RecycleBin() 33 | { 34 | Run("::{645ff040-5081-101b-9f08-00aa002f954e}"); 35 | } 36 | 37 | 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /_sharpAHK/_Zip.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.IO.Compression; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading; 8 | using System.Threading.Tasks; 9 | 10 | namespace sharpAHK 11 | { 12 | public partial class _AHK 13 | { 14 | // === Zip === 15 | 16 | // using System.IO.Compression; 17 | 18 | /// Add File to New or Existing .Zip File 19 | /// FilePath to add to New/Existing Zip File 20 | /// New/Existing Zip File to Add File To 21 | /// Option to add Zip File Fastest Method (Slower = Smaller File) 22 | /// False = File in Root of Zip File, True = Full folder structure as found in original file path 23 | /// 24 | /// bool Zipped = ahk.Zip(FilePath, newZip, false, false, false); // places file in root of zip file 25 | /// bool Zipped = ahk.Zip(FilePath, newZip, false, false, true); // places file in same folder structure as found on location drive (buried in sub folders under drive letter inside zip) 26 | /// 27 | public bool Zip(string FileToZip, string zipFile = "", bool Fastest = true, bool FullPath = false) 28 | { 29 | bool RelativeToRoot = false; // doesn't seem to make a diff 30 | 31 | //bool DeleteExistingZip = true; 32 | //if (DeleteExistingZip) { FileDelete(zipFile); } 33 | 34 | // if user passes in a directory to zip - use ZipDir function 35 | if (IsDir(FileToZip)) { ZipDir(FileToZip, zipFile); return true; } 36 | 37 | // update / add to existing zip file 38 | if (File.Exists(zipFile)) 39 | { 40 | try 41 | { 42 | string EntryPath = FileName(FileToZip); 43 | 44 | //bool FullPath = false; 45 | if (FullPath) { EntryPath = FileToZip; } 46 | 47 | //bool RelativeToRoot = true; 48 | //if (OutDirPath == "SameDirAsFile") { RelativeToRoot = true; } 49 | 50 | //string RootDir = @"C:\Users\Jason\Google Drive\IMDB\"; 51 | //if (RelativeToRoot) { EntryPath = StringReplace(FileToZip, RootDir); } 52 | 53 | CompressionLevel compLevel = CompressionLevel.Fastest; 54 | if (!Fastest) { compLevel = CompressionLevel.Optimal; } 55 | 56 | using (var fileStream = new FileStream(zipFile, FileMode.Open)) 57 | { 58 | using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Update, true)) 59 | { 60 | byte[] bytes = System.IO.File.ReadAllBytes(FileToZip); 61 | var zipArchiveEntry = archive.CreateEntry(EntryPath, compLevel); 62 | using (var zipStream = zipArchiveEntry.Open()) 63 | zipStream.Write(bytes, 0, bytes.Length); 64 | } 65 | } 66 | } 67 | catch 68 | { 69 | return false; 70 | } 71 | } 72 | 73 | // create new zip file if it doesn't exist yet 74 | if (!File.Exists(zipFile)) 75 | { 76 | 77 | string EntryPath = FileName(FileToZip); 78 | 79 | //bool FullPath = false; 80 | if (FullPath) { EntryPath = FileToZip; } 81 | 82 | //bool RelativeToRoot = true; 83 | string RootDir = FileDir(FileToZip); 84 | if (zipFile != "") { RootDir = FileDir(zipFile); } 85 | 86 | if (RelativeToRoot) { EntryPath = StringReplace(FileToZip, RootDir + "\\"); } 87 | 88 | 89 | try 90 | { 91 | using (var fileStream = new FileStream(zipFile, FileMode.CreateNew)) 92 | { 93 | using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true)) 94 | { 95 | byte[] bytes = System.IO.File.ReadAllBytes(FileToZip); 96 | var zipArchiveEntry = archive.CreateEntry(EntryPath, CompressionLevel.Fastest); 97 | using (var zipStream = zipArchiveEntry.Open()) 98 | zipStream.Write(bytes, 0, bytes.Length); 99 | } 100 | } 101 | 102 | } 103 | catch 104 | { 105 | return false; 106 | } 107 | } 108 | 109 | // for moving zip files to new dirs as zipping 110 | 111 | //Sleep(1000); 112 | //string newZipLocation = FileDir(zipFile) + "\\Zip_Files"; 113 | //string newFileLocation = FileDir(zipFile) + "\\Zipped"; 114 | //FileCreateDir(newZipLocation); 115 | //FileCreateDir(newFileLocation); 116 | //FileMove(zipFile, FileDir(newZipLocation + "\\" + FileName(zipFile), false)); 117 | //FileMove(FileToZip, FileDir(newFileLocation + "\\" + FileName(FileToZip), false)); 118 | 119 | return true; 120 | } 121 | 122 | /// Add Folder to Zip File 123 | /// Path of Directory to Zip 124 | /// New/Existing Zip File to Add Folder To 125 | /// Either Fastest speed (True) or (False) for Optimal Compression level 126 | /// Default option to include base directory in zip file structure 127 | public bool ZipDir(string DirToZip, string zipFile, bool Fastest = true, bool IncludeBaseDir = true) 128 | { 129 | FileDelete(zipFile); 130 | 131 | if (Fastest) { ZipFile.CreateFromDirectory(DirToZip, zipFile, CompressionLevel.Fastest, IncludeBaseDir); } 132 | else { ZipFile.CreateFromDirectory(DirToZip, zipFile, CompressionLevel.Optimal, IncludeBaseDir); } 133 | 134 | return true; 135 | } 136 | 137 | /// Unzip Zip File to Directory 138 | /// Zip File Path 139 | /// Location to Unzip Files To (If Blank Unzips To ZipFileDir\ZipFileName 140 | public bool UnZip(string zipFile, string UnZipDir = "") 141 | { 142 | if (UnZipDir == "") { UnZipDir = FileDir(zipFile) + "\\" + FileNameNoExt(zipFile); } 143 | 144 | try 145 | { 146 | ZipFile.ExtractToDirectory(zipFile, UnZipDir); 147 | return true; 148 | } 149 | catch 150 | { 151 | return false; 152 | } 153 | } 154 | 155 | /// Loop through DirPath and create new ZIP file for each file in directory 156 | /// 157 | /// 158 | /// 159 | public void ZipEachFile(string DirPath, bool Fastest = true, string ZipSaveDir = "", string SearchPattern = "*.*", bool Recurse = false) 160 | { 161 | List fileList = new List(); 162 | 163 | string[] files = null; 164 | if (Recurse) { files = Directory.GetFiles(DirPath, SearchPattern, System.IO.SearchOption.AllDirectories); } 165 | if (!Recurse) { files = Directory.GetFiles(DirPath, SearchPattern, System.IO.SearchOption.TopDirectoryOnly); } 166 | 167 | foreach (string file in files) // loop through directory and return list of directories under DirPath 168 | { 169 | fileList.Add(file); 170 | } 171 | 172 | int zippedCount = 0; 173 | string zipSaveDir = DirPath; 174 | foreach (string f in fileList) 175 | { 176 | zippedCount++; 177 | 178 | // update displayControl Text with progress (if user defined this control name) 179 | DisplayText("Zipping File " + f + "..."); 180 | 181 | string fileNameNoExt = FileNameNoExt(f); 182 | 183 | if (ZipSaveDir.Trim() != "") { zipSaveDir = ZipSaveDir; } 184 | if (ZipSaveDir.Trim() == "") { zipSaveDir = DirPath; } 185 | 186 | FileCreateDir(zipSaveDir); // ensure save directory exists 187 | 188 | 189 | string newZip = zipSaveDir + "\\" + fileNameNoExt + ".zip"; 190 | 191 | Zip(f, newZip, Fastest); 192 | 193 | //MsgBox("Zipped Dir " + zippedCount.ToString() + " / " + dirList.Count.ToString()); 194 | } 195 | 196 | // update displayControl Text with progress (if user defined this control name) 197 | DisplayText("Finished Zipping " + zippedCount.ToString() + " + Files"); 198 | 199 | //MsgBox("Finished Zipping " + zippedCount.ToString() + " Directories"); 200 | 201 | //string DirName = FileName(file); // name of the folder 202 | 203 | } 204 | 205 | /// Loop through DirPath and create new ZIP file for each folder in directory [CREATES NEW THREAD] 206 | /// Root directory to search for folders to zip 207 | /// Compression Method, Fastest = true, Optimal = false 208 | /// Search pattern for folder names to zip 209 | public void ZipEachFile_NewThread(string DirPath, bool Fastest = true, string ZipSaveDir = "", string SearchPattern = "*.*", bool Recurse = false) 210 | { 211 | Thread zipthread = new Thread(() => ZipEachFile(DirPath, Fastest, ZipSaveDir, SearchPattern, Recurse)); 212 | zipthread.Start(); 213 | } 214 | 215 | 216 | /// Loop through DirPath and create new ZIP file for each folder in directory 217 | /// Root directory to search for folders to zip 218 | /// Compression Method, Fastest = true, Optimal = false 219 | /// Search pattern for folder names to zip 220 | public void ZipEachDir(string DirPath, bool Fastest = true, string SearchPattern = "*.*") 221 | { 222 | List dirList = new List(); 223 | 224 | bool Recurse = false; 225 | string[] dirPaths = null; 226 | if (Recurse) { dirPaths = Directory.GetDirectories(DirPath, SearchPattern, System.IO.SearchOption.AllDirectories); } 227 | if (!Recurse) { dirPaths = Directory.GetDirectories(DirPath, SearchPattern, System.IO.SearchOption.TopDirectoryOnly); } 228 | 229 | foreach (string dir in dirPaths) // loop through directory and return list of directories under DirPath 230 | { 231 | dirList.Add(dir); 232 | } 233 | 234 | int zippedCount = 0; 235 | foreach (string Directory in dirList) 236 | { 237 | zippedCount++; 238 | 239 | // update displayControl Text with progress (if user defined this control name) 240 | DisplayText("Zipping Directory " + zippedCount + " / " + dirList.Count.ToString() + "..."); 241 | 242 | string dirName = DirName(Directory); 243 | 244 | string newZip = DirPath + "\\" + dirName + ".zip"; 245 | 246 | ZipDir(Directory, newZip, Fastest); 247 | 248 | //MsgBox("Zipped Dir " + zippedCount.ToString() + " / " + dirList.Count.ToString()); 249 | } 250 | 251 | // update displayControl Text with progress (if user defined this control name) 252 | DisplayText("Finished Zipping " + zippedCount + " Directories"); 253 | 254 | MsgBox("Finished Zipping " + zippedCount.ToString() + " Directories"); 255 | 256 | //string DirName = FileName(file); // name of the folder 257 | 258 | } 259 | 260 | /// Loop through DirPath and create new ZIP file for each folder in directory [CREATES NEW THREAD] 261 | /// Root directory to search for folders to zip 262 | /// Compression Method, Fastest = true, Optimal = false 263 | /// Search pattern for folder names to zip 264 | public void ZipEachDir_NewThread(string DirPath, bool Fastest = true, string SearchPattern = "*.*") 265 | { 266 | Thread zipthread = new Thread(() => ZipEachDir(DirPath, Fastest, SearchPattern)); 267 | zipthread.Start(); 268 | } 269 | 270 | 271 | 272 | } 273 | } 274 | -------------------------------------------------------------------------------- /app.config: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /lib/AutoHotkey/AutoHotkey.chm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/lib/AutoHotkey/AutoHotkey.chm -------------------------------------------------------------------------------- /lib/AutoHotkey/AutoHotkey.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/lib/AutoHotkey/AutoHotkey.exe -------------------------------------------------------------------------------- /lib/Util/AhkEscape.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoHotkey.Interop 8 | { 9 | class AhkEscape 10 | { 11 | 12 | /// 13 | /// Checks to see if C# string already has quotes, adjust for escape characters 14 | /// 15 | /// 16 | /// 17 | public static string Quote(string msg) { 18 | if (msg == null) throw new ArgumentNullException("msg"); 19 | 20 | bool alreadyQuoted = msg.StartsWith("\"") && msg.EndsWith("\""); 21 | 22 | if (alreadyQuoted) { 23 | //remove quotes, and then escape 24 | msg = msg.Remove(0, 1); 25 | msg = msg.Remove(msg.Length - 1, 1); 26 | msg = "\"" + Escape(msg) + "\""; 27 | } 28 | else { 29 | msg = "\"" + Escape(msg) + "\""; 30 | } 31 | 32 | return msg; 33 | } 34 | 35 | /// 36 | /// Convert C# Escape Characters into AutoHotkey Escapes 37 | /// 38 | /// 39 | /// 40 | public static string Escape(string msg) { 41 | if (msg == null) throw new ArgumentNullException("msg"); 42 | 43 | return msg 44 | .Replace("`", "``") 45 | .Replace("\r", "`r") 46 | .Replace("\n", "`n") 47 | .Replace("\t", "`t") 48 | .Replace("\"", "\"\""); 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /lib/Util/AutoHotkeyDllLoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Text; 6 | using System.Threading.Tasks; 7 | 8 | namespace AutoHotkey.Interop.Util 9 | { 10 | internal static class AutoHotkeyDllLoader 11 | { 12 | private static readonly Lazy dllHandle 13 | = new Lazy(LoadDll); 14 | 15 | 16 | internal static void EnsureDllIsLoaded() { 17 | if (dllHandle.IsValueCreated) 18 | return; 19 | 20 | var handle = dllHandle.Value; 21 | } 22 | 23 | private static SafeLibraryHandle LoadDll() { 24 | //determine if we should use x86/AutoHotkey.dll or x64/AutoHotkey.dll 25 | //then try to load it by the file directory or 26 | //extract the embeded ones into a temp directory 27 | //and load them 28 | 29 | string processor_type = ProcessorType.Is32Bit() ? "x86" : "x64"; 30 | //string relativePath = processor_type + "/AutoHotkey.dll"; 31 | string relativePath = "lib/Util/" + processor_type + "/AutoHotkey.dll"; 32 | 33 | if (File.Exists(relativePath)) { 34 | return SafeLibraryHandle.LoadLibrary(relativePath); 35 | } 36 | else { 37 | return ExtractAndLoadEmbededResource(relativePath); 38 | } 39 | } 40 | 41 | private static SafeLibraryHandle ExtractAndLoadEmbededResource(string relativePath) { 42 | var assembly = typeof(AutoHotkeyEngine).Assembly; 43 | var resource = EmbededResourceHelper.FindByName(assembly, relativePath); 44 | 45 | if (resource != null) { 46 | string tempFolderPath = GetTempFolderPath(); 47 | var output_file = Path.Combine(tempFolderPath, relativePath); 48 | EmbededResourceHelper.ExtractToFile(assembly, resource, output_file); 49 | return SafeLibraryHandle.LoadLibrary(output_file); 50 | } 51 | 52 | return null; 53 | } 54 | 55 | private static string GetTempFolderPath() { 56 | string temp = Path.GetTempPath(); 57 | string ahk = "AutoHotkey.Interop"; 58 | string version = typeof(AutoHotkeyEngine).Assembly.GetName().Version.ToString(); 59 | return Path.Combine(temp, ahk, version); 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /lib/Util/AutoHotkeyEngine.cs: -------------------------------------------------------------------------------- 1 | using AutoHotkey.Interop.Util; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Runtime.InteropServices; 7 | using System.Text; 8 | using System.Threading.Tasks; 9 | 10 | namespace AutoHotkey.Interop 11 | { 12 | /// 13 | /// This class expects an AutoHotkey.dll to be available on the machine. (UNICODE) version. 14 | /// 15 | public class AutoHotkeyEngine 16 | { 17 | public static AutoHotkeyEngine Instance { get { return lazyInstance.Value; } } 18 | private static Lazy lazyInstance = 19 | new Lazy(() => new AutoHotkeyEngine()); 20 | 21 | public AutoHotkeyEngine() { 22 | Util.AutoHotkeyDllLoader.EnsureDllIsLoaded(); 23 | AutoHotkeyDll.ahktextdll("", "", ""); 24 | } 25 | 26 | /// 27 | /// Gets the value for a varible or an empty string if the variable does not exist. 28 | /// 29 | /// Name of the variable. 30 | /// Returns the value of the variable, or an empty string if the variable does not exist. 31 | public string GetVar(string variableName) 32 | { 33 | var p = AutoHotkeyDll.ahkgetvar(variableName, 0); 34 | return Marshal.PtrToStringUni(p); 35 | } 36 | 37 | /// 38 | /// Sets the value of a variable. 39 | /// 40 | /// Name of the variable. 41 | /// The value to set. 42 | public void SetVar(string variableName, string value) 43 | { 44 | if (value == null) 45 | value = ""; 46 | 47 | AutoHotkeyDll.ahkassign(variableName, value); 48 | } 49 | 50 | /// 51 | /// Determines whether state is "Ready" or not (thanks to burque505) 52 | /// 53 | /// No parameters 54 | /// Returns true if the state is "Ready", otherwise false 55 | public bool IsReady() 56 | { 57 | if (AutoHotkeyDll.ahkReady() == true) 58 | { 59 | return true; 60 | } 61 | else 62 | { 63 | return false; 64 | } 65 | } 66 | 67 | /// 68 | /// Evaulates an expression or function and returns the results 69 | /// 70 | /// The code to execute 71 | /// Returns the result of an expression 72 | public string Eval(string code) 73 | { 74 | var codeToRun = "A__EVAL:=" + code; 75 | AutoHotkeyDll.ahkExec(codeToRun); 76 | return GetVar("A__EVAL"); 77 | } 78 | 79 | /// 80 | /// Loads a file into the running script 81 | /// 82 | /// The filepath of the script 83 | /// Option to add return in front of code added to keep from executing on startup 84 | public void LoadFile(string filePath, bool AddReturn = false) 85 | { 86 | var absolute_file_path = Path.GetFullPath(filePath); 87 | 88 | //AutoHotkeyDll.addFile(absolute_file_path, 1, 1); 89 | string script = File.ReadAllText(filePath); 90 | 91 | if (AddReturn) { script = "return\n\n" + script; } // option to add return in front of code added to keep from executing on startup 92 | 93 | this.LoadScript(script); 94 | } 95 | 96 | public void LoadScript(string scriptText) { 97 | AutoHotkeyDll.addScript(scriptText, AutoHotkeyDll.Execute.RunWait); 98 | } 99 | /// 100 | /// Executes raw ahk code. 101 | /// 102 | /// The code to execute 103 | public void ExecRaw(string code) 104 | { 105 | AutoHotkeyDll.ahkExec(code); 106 | } 107 | 108 | /// 109 | /// Terminates running scripts 110 | /// 111 | public void Terminate() 112 | { 113 | AutoHotkeyDll.ahkTerminate(1000); 114 | } 115 | 116 | public void Reset() { 117 | Terminate(); 118 | AutoHotkeyDll.ahkReload(); 119 | AutoHotkeyDll.ahktextdll("", "", ""); 120 | } 121 | 122 | /// 123 | /// Suspends AHK Scripts 124 | /// 125 | public void Suspend() 126 | { 127 | ExecRaw("Suspend, On"); 128 | } 129 | 130 | /// 131 | /// Unsuspends AHK Scripts 132 | /// 133 | public void UnSuspend() 134 | { 135 | ExecRaw("Suspend, Off"); 136 | } 137 | 138 | /// 139 | /// Executes an already defined function. 140 | /// 141 | /// The name of the function to execute. 142 | /// The 1st parameter 143 | /// The 2nd parameter 144 | /// The 3rd parameter 145 | /// The 4th parameter 146 | /// The 5th parameter 147 | /// The 6th parameter 148 | /// The 7th parameter 149 | /// The 8th parameter 150 | /// The 9th parameter 151 | /// The 10 parameter 152 | public string ExecFunction(string functionName, 153 | string param1 = null, 154 | string param2 = null, 155 | string param3 = null, 156 | string param4 = null, 157 | string param5 = null, 158 | string param6 = null, 159 | string param7 = null, 160 | string param8 = null, 161 | string param9 = null, 162 | string param10 = null) 163 | { 164 | IntPtr ret = AutoHotkeyDll.ahkFunction(functionName, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10); 165 | 166 | if (ret == IntPtr.Zero) 167 | return null; 168 | else 169 | return Marshal.PtrToStringUni(ret); 170 | } 171 | 172 | 173 | /// 174 | /// Determines if the function exists. 175 | /// 176 | /// Name of the function. 177 | /// Returns true if the function exists, otherwise false. 178 | public bool FunctionExists(string functionName) 179 | { 180 | IntPtr funcptr = AutoHotkeyDll.ahkFindFunc(functionName); 181 | return funcptr != IntPtr.Zero; 182 | } 183 | 184 | /// 185 | /// Executes a label 186 | /// 187 | /// Name of the label. 188 | public void ExecLabel(string labelName) 189 | { 190 | AutoHotkeyDll.ahkLabel(labelName, false); 191 | } 192 | 193 | /// 194 | /// Determines if the label exists. 195 | /// 196 | /// Name of the label. 197 | /// Returns true if the label exists, otherwise false 198 | public bool LabelExists(string labelName) 199 | { 200 | IntPtr labelptr = AutoHotkeyDll.ahkFindLabel(labelName); 201 | return labelptr != IntPtr.Zero; 202 | } 203 | 204 | /// 205 | /// Enables communication between AutoHotkey code and the hosting enviorment. 206 | /// This module imports an AHK function named SendPipeMessage that you can use 207 | /// call the specified handler. 208 | /// 209 | /// The handler that will receive the SendPipesMessage from AHK. 210 | public void InitalizePipesModule(Func sendPipeMessageHandler) { 211 | Pipes.PipesModuleLoader.LoadPipesModule(sendPipeMessageHandler); 212 | } 213 | } 214 | } 215 | -------------------------------------------------------------------------------- /lib/Util/EmbededResourceHelper.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Text; 7 | using System.Text.RegularExpressions; 8 | using System.Threading.Tasks; 9 | 10 | namespace AutoHotkey.Interop.Util 11 | { 12 | internal static class EmbededResourceHelper 13 | { 14 | public static string FindByName(Assembly assembly, string path) { 15 | path = Regex.Replace(path, @"[/\\]", "."); //replace slashes with periods 16 | string path_with_dot_prefix = path.StartsWith(".") ? path : "." + path; 17 | 18 | var names = assembly.GetManifestResourceNames(); 19 | 20 | foreach (var name in names) { 21 | if (name.EndsWith(path_with_dot_prefix, StringComparison.InvariantCultureIgnoreCase)) 22 | return name; 23 | if (name.Equals(path, StringComparison.InvariantCultureIgnoreCase)) 24 | return name; 25 | } 26 | 27 | return null; 28 | } 29 | 30 | 31 | public static void ExtractToFile(Assembly assembly, string embededResourceName, string outputFilePath) { 32 | string full_resource_name = FindByName(assembly, embededResourceName); 33 | 34 | if (full_resource_name == null) 35 | throw new FileNotFoundException(string.Format("Cannot find resource name of '{0}' in assembly '{1}'", embededResourceName, assembly.GetName().Name), embededResourceName); 36 | 37 | EnsureDirectoryExistsForFile(outputFilePath); 38 | 39 | using (var readStream = assembly.GetManifestResourceStream(full_resource_name)) 40 | try 41 | { 42 | using (var writeStream = File.Open(outputFilePath, FileMode.Create)) 43 | { 44 | readStream.CopyTo(writeStream); 45 | readStream.Flush(); 46 | } 47 | } 48 | catch { } 49 | 50 | } 51 | 52 | public static string ExtractToText(Assembly assembly, string embededResourceName) { 53 | string full_resource_name = FindByName(assembly, embededResourceName); 54 | if (full_resource_name == null) 55 | throw new FileNotFoundException(string.Format("Cannot find resource name of '{0}' in assembly '{1}'", embededResourceName, assembly.GetName().Name), embededResourceName); 56 | using (var readStream = assembly.GetManifestResourceStream(full_resource_name)) 57 | using (StreamReader reader = new StreamReader(readStream)) 58 | return reader.ReadToEnd(); 59 | } 60 | 61 | private static void EnsureDirectoryExistsForFile(string targetFileName) { 62 | var absolutePath = Path.GetFullPath(targetFileName); 63 | var directoryPath = Path.GetDirectoryName(absolutePath); 64 | 65 | if (!Directory.Exists(directoryPath)) 66 | Directory.CreateDirectory(directoryPath); 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /lib/Util/Pipes/MessageHandlerPipeServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoHotkey.Interop.Pipes 8 | { 9 | internal class MessageHandlerPipeServer : NamedPipeServer 10 | { 11 | Func messageHandler = null; 12 | 13 | public MessageHandlerPipeServer(string pipeName, Func messageHandler) : base(pipeName) { 14 | if (pipeName == null) throw new ArgumentNullException("pipeName"); 15 | if (messageHandler == null) throw new ArgumentNullException("messageHandler"); 16 | 17 | this.messageHandler = messageHandler; 18 | } 19 | 20 | protected override string HandleClientMessage(string clientMessage) { 21 | return messageHandler(clientMessage); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /lib/Util/Pipes/NamedPipeServer.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.IO.Pipes; 5 | using System.Linq; 6 | using System.Text; 7 | using System.Threading.Tasks; 8 | 9 | namespace AutoHotkey.Interop.Pipes 10 | { 11 | internal abstract class NamedPipeServer 12 | { 13 | private readonly string pipeName; 14 | private volatile NamedPipeServerStream serverStream; 15 | 16 | public bool IsClientConnected { 17 | get { 18 | if (serverStream == null) 19 | return false; 20 | else 21 | return serverStream.IsConnected; 22 | } 23 | } 24 | 25 | public NamedPipeServer(string pipeName) { 26 | this.pipeName = pipeName; 27 | } 28 | 29 | public void Start() { 30 | serverStream = MakeNamedPipeServerStream(pipeName); 31 | serverStream.BeginWaitForConnection(DoConnectionLoop, null); 32 | } 33 | 34 | private async void DoConnectionLoop(IAsyncResult result) { 35 | if (!result.IsCompleted) return; 36 | if (serverStream == null) return; 37 | 38 | //IOException = pipe is broken 39 | //ObjectDisposedException = cannot access closed pipe 40 | //OperationCanceledException - read was canceled 41 | 42 | //ACCEPT CLIENT CONNECTION 43 | try { 44 | serverStream.EndWaitForConnection(result); 45 | } 46 | catch (IOException) { RebuildNamedPipe(); return; } 47 | catch (ObjectDisposedException) { RebuildNamedPipe(); return; } 48 | catch (OperationCanceledException) { RebuildNamedPipe(); return; } 49 | 50 | while (IsClientConnected) { 51 | string clientMessage = null; 52 | string serverResponce = null; 53 | 54 | // READ FROM CLIENT 55 | if (serverStream == null) break; 56 | try { 57 | clientMessage = await ReadClientMessage(serverStream); 58 | } 59 | catch (IOException) { RebuildNamedPipe(); return; } 60 | catch (ObjectDisposedException) { RebuildNamedPipe(); return; } 61 | catch (OperationCanceledException) { RebuildNamedPipe(); return; } 62 | 63 | //PROCESS CLIENT MESSAGE 64 | serverResponce = HandleClientMessage(clientMessage); 65 | 66 | 67 | 68 | //SEND RESPONCE BACK TO CLIENT 69 | if (serverStream == null) break; 70 | try { 71 | await SendResponceToClient(serverStream, serverResponce); 72 | } 73 | catch (IOException) { RebuildNamedPipe(); return; } 74 | catch (ObjectDisposedException) { RebuildNamedPipe(); return; } 75 | catch (OperationCanceledException) { RebuildNamedPipe(); return; } 76 | } 77 | 78 | //client disconnected, relisten 79 | if (serverStream != null) 80 | serverStream.BeginWaitForConnection(DoConnectionLoop, null); 81 | } 82 | 83 | private void RebuildNamedPipe() { 84 | this.Shutdown(); 85 | serverStream = MakeNamedPipeServerStream(pipeName); 86 | serverStream.BeginWaitForConnection(DoConnectionLoop, null); 87 | } 88 | 89 | protected abstract string HandleClientMessage(string clientMessage); 90 | 91 | private static async Task SendResponceToClient(NamedPipeServerStream stream, string serverResponce) { 92 | byte[] responceData = Encoding.Unicode.GetBytes(serverResponce); 93 | await stream.WriteAsync(responceData, 0, responceData.Length); 94 | await stream.FlushAsync(); 95 | stream.WaitForPipeDrain(); 96 | } 97 | 98 | private static async Task ReadClientMessage(NamedPipeServerStream stream) { 99 | byte[] buffer = new byte[65535]; 100 | int read = await stream.ReadAsync(buffer, 0, buffer.Length); 101 | string clientString = Encoding.Unicode.GetString(buffer, 0, read); 102 | return clientString; 103 | } 104 | 105 | public void Shutdown() { 106 | if (serverStream != null) { 107 | try { serverStream.Close(); } catch { } 108 | try { serverStream.Dispose(); } catch { } 109 | serverStream = null; 110 | } 111 | } 112 | 113 | 114 | private NamedPipeServerStream MakeNamedPipeServerStream(string pipeName) { 115 | return new System.IO.Pipes.NamedPipeServerStream(pipeName, 116 | System.IO.Pipes.PipeDirection.InOut, 117 | System.IO.Pipes.NamedPipeServerStream.MaxAllowedServerInstances, 118 | System.IO.Pipes.PipeTransmissionMode.Byte, 119 | System.IO.Pipes.PipeOptions.Asynchronous); 120 | } 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /lib/Util/Pipes/PipesModuleLoader.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoHotkey.Interop.Pipes 8 | { 9 | public static class PipesModuleLoader 10 | { 11 | public static object lockObj = new object(); 12 | internal static MessageHandlerPipeServer Server { get; private set; } 13 | 14 | public static void LoadPipesModule(Func messageHandler) { 15 | lock (lockObj) { 16 | var pipename = GeneratePipeName(); 17 | InitPipeServer(pipename, messageHandler); 18 | InitPipeClient(pipename); 19 | } 20 | } 21 | 22 | private static void InitPipeClient(string pipename) { 23 | //only load pipe client once, by checking for pipeclient_getversion function 24 | if (!AutoHotkeyEngine.Instance.FunctionExists("pipeclient_getversion")) { 25 | var ahk_pipeclient_lib = Util.EmbededResourceHelper.ExtractToText(typeof(PipesModuleLoader).Assembly, "Pipes/pipeclient.ahk"); 26 | AutoHotkeyEngine.Instance.LoadScript(ahk_pipeclient_lib); 27 | } 28 | else { 29 | AutoHotkeyEngine.Instance.LoadScript("A__PIPECLIENT.close()"); 30 | } 31 | 32 | AutoHotkeyEngine.Instance.LoadScript(string.Format( 33 | "A__PIPECLIENT := new pipeclient({0})", 34 | AhkEscape.Quote(pipename))); 35 | } 36 | 37 | private static void InitPipeServer(string pipename, Func messageHandler) { 38 | if (Server != null) { 39 | Server.Shutdown(); 40 | } 41 | 42 | Server = new MessageHandlerPipeServer(pipename, messageHandler); 43 | Server.Start(); 44 | } 45 | 46 | private static string GeneratePipeName() { 47 | return "AHK-PIPE-" + Guid.NewGuid().ToString().Replace("-", ""); 48 | } 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /lib/Util/Pipes/pipeclient.ahk: -------------------------------------------------------------------------------- 1 | __showvar(msg, var) { 2 | msgbox % msg . " =`r`n`r`n" . var 3 | } 4 | 5 | __showlasterror() { 6 | __showvar("last error", A_LastError) 7 | } 8 | 9 | 10 | SendPipeMessage(strMessage) { 11 | global A__PIPECLIENT 12 | A__PIPECLIENT.write(strMessage) 13 | sleep, 100 14 | A__PIPECLIENT_RESULT := A__PIPECLIENT.read() 15 | sleep, 100 16 | return A__PIPECLIENT_RESULT 17 | } 18 | 19 | ; get version - also required to make sure pipe client is not loaded twice 20 | pipeclient_getversion() { 21 | return "v1.0" 22 | } 23 | 24 | pipeclient_log(strMessage) { 25 | 26 | } 27 | 28 | class WinApiErrorCodes { 29 | static ERROR_PIPE_NOT_CONNECTED := 233 30 | static ERROR_INVALID_HANDLE := 6 31 | static ERROR_PIPE_BUSY := 231 32 | static ERROR_NOACCESS := 998 33 | } 34 | 35 | class pipeclient { 36 | pipe_name := "" 37 | pipe_handle := "" 38 | 39 | 40 | __New(name) { 41 | this.pipe_name := this.__get_full_pipe_name(name) 42 | this.pipe_handle := this.__get_pipe_handle(this.pipe_name) 43 | } 44 | 45 | 46 | is_connected() { 47 | b := this.get_bytes_to_read() ; call the peeknamedpipe, in order to check last error 48 | return A_LastError == 0 ; this will be something like '233' if there was an error 49 | } 50 | 51 | 52 | get_bytes_to_read() { 53 | buffer_size := 2 54 | buffer := "" 55 | VarSetCapacity(buffer, buffer_size) 56 | 57 | bytes_read := 0 58 | total_bytes_available := 0 59 | bytes_left_in_message := 0 60 | 61 | ret := DllCall("PeekNamedPipe" 62 | ,"Ptr", this.pipe_handle 63 | ,"Ptr", &buffer 64 | ,"Uint*", buffer_size 65 | ,"Uint*", bytes_read 66 | ,"Uint*", total_bytes_available 67 | ,"Uint*", bytes_left_in_message) 68 | 69 | 70 | if (ret == 0) ; no data to read 71 | { 72 | ; MsgBox, problem peeking 73 | ; showlasterror() 74 | return -1 75 | } 76 | else 77 | { 78 | return total_bytes_available 79 | } 80 | } 81 | 82 | 83 | wait_for_data_to_read(max_wait_time := 0) { 84 | waited := 0 85 | step := 100 86 | 87 | buffer_size := this.get_bytes_to_read() 88 | 89 | while (buffer_size <= 0) { 90 | Sleep, %step% 91 | waited := waited + step 92 | 93 | if (max_wait_time > 0 && waited >= max_wait_time) 94 | return False 95 | 96 | buffer_size := this.get_bytes_to_read() 97 | } 98 | 99 | return True 100 | } 101 | 102 | read() { 103 | wait_result := this.wait_for_data_to_read() ;wait infintely for data 104 | ;showvar("read - wait result", wait_result) 105 | 106 | buffer_size := this.get_bytes_to_read() 107 | ;showvar("read - buffer_size", buffer_size) 108 | 109 | buffer := "" 110 | VarSetCapacity(buffer, buffer_size) 111 | 112 | ret := DllCall("ReadFile" 113 | ,"Ptr", this.pipe_handle 114 | ,"Str", buffer 115 | ,"UInt", buffer_size 116 | ,"UInt*", bytes_read 117 | ,"UInt", 0) 118 | 119 | ; Trim results data down to only the bytes read 120 | ; use memcpy to do this 121 | if (ret == 1) ; if read was successful 122 | { 123 | result := "" 124 | VarSetCapacity(result, bytes_read) 125 | DllCall("msvcrt\memcpy", "str", result, "ptr", &buffer, "ptr", bytes_read) 126 | ;showvar("read - results", result) 127 | return result 128 | } 129 | else { ;read failed due to error 130 | return 131 | } 132 | } 133 | 134 | write(msg) { 135 | ;add in BOM 136 | ;msg := (A_IsUnicode ? chr(0xfeff) : chr(239) chr(187) chr(191)) . msg 137 | 138 | buffer := msg 139 | buffer_length := (A_IsUnicode ? StrLen(buffer) * 2 : StrLen(buffer)) 140 | num_of_bytes_written := 0 141 | 142 | DllCall("WriteFile" 143 | ,"Ptr", this.pipe_handle 144 | ,"Str", buffer 145 | ,"UInt", buffer_length 146 | ,"UInt*", bytes_written 147 | ,"UInt", 0) 148 | 149 | return bytes_written 150 | } 151 | 152 | close() { 153 | DllCall("CloseHandle", "Ptr", this.pipe_handle) 154 | } 155 | 156 | 157 | __get_full_pipe_name(name) { 158 | if (RegExMatch(name, "^\\\\.\\pipe\\")) 159 | return name 160 | else 161 | return "\\.\pipe\" . name 162 | } 163 | 164 | __get_pipe_handle(name) { 165 | GENERIC_WRITE := 0x40000000 166 | GENERIC_READ := 0x80000000 167 | access := GENERIC_READ | GENERIC_WRITE 168 | 169 | return DllCall("CreateFile" 170 | ,"Str" , name 171 | ,"UInt", access 172 | ,"UInt", 3 ; share read / write 173 | ,"UInt", 0 174 | ,"UInt", 3 ; open existing file 175 | ,"UInt", 0 176 | ,"UInt", 0) 177 | } 178 | } 179 | 180 | 181 | 182 | -------------------------------------------------------------------------------- /lib/Util/ProcessorType.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | 7 | namespace AutoHotkey.Interop.Util 8 | { 9 | internal static class ProcessorType 10 | { 11 | public static bool Is64Bit() { 12 | return IntPtr.Size == 8; 13 | } 14 | public static bool Is32Bit() { 15 | return IntPtr.Size == 4; 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /lib/Util/SafeLibraryHandle.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Win32.SafeHandles; 2 | using System; 3 | using System.Collections.Generic; 4 | using System.Linq; 5 | using System.Runtime.ConstrainedExecution; 6 | using System.Runtime.InteropServices; 7 | using System.Security; 8 | using System.Security.Permissions; 9 | using System.Text; 10 | using System.Threading.Tasks; 11 | 12 | namespace AutoHotkey.Interop 13 | { 14 | [SecurityPermission(SecurityAction.LinkDemand, UnmanagedCode = true)] 15 | internal sealed class SafeLibraryHandle : SafeHandleZeroOrMinusOneIsInvalid 16 | { 17 | #region Native Calls 18 | 19 | [DllImport("kernel32.dll", SetLastError = true)] 20 | public static extern SafeLibraryHandle LoadLibrary(string lpFileName); 21 | 22 | [SuppressUnmanagedCodeSecurity] 23 | [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] 24 | [DllImport("kernel32.dll", SetLastError = true)] 25 | private static extern bool FreeLibrary(IntPtr hModule); 26 | 27 | #endregion 28 | 29 | private SafeLibraryHandle() : base(true) { } 30 | 31 | protected override bool ReleaseHandle() 32 | { 33 | return FreeLibrary(handle); 34 | } 35 | 36 | protected override void Dispose(bool disposing) 37 | { 38 | base.Dispose(disposing); 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /lib/Util/x64/AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/lib/Util/x64/AutoHotkey.dll -------------------------------------------------------------------------------- /lib/Util/x64/v2_AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/lib/Util/x64/v2_AutoHotkey.dll -------------------------------------------------------------------------------- /lib/Util/x86/AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/lib/Util/x86/AutoHotkey.dll -------------------------------------------------------------------------------- /lib/Util/x86/v2_AutoHotkey.dll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/LucidMethod/sharpAHK/356340c1a9b970510891d509d236c0d6e983e36d/lib/Util/x86/v2_AutoHotkey.dll -------------------------------------------------------------------------------- /packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /sharpAHK.csproj.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | sharpAHK 5 | LucidMethod 6 | 1.0.0.8 7 | LucidMethod 8 | https://github.com/LucidMethod 9 | https://github.com/LucidMethod 10 | https://github.com/LucidMethod/icon.ico 11 | false 12 | AutoHotkey for C# 13 | SharpAHK Release 14 | Copyright 2020 15 | sharpAHK AutoHotkey 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /sharpAHK.csproj.vspscc: -------------------------------------------------------------------------------- 1 | "" 2 | { 3 | "FILE_VERSION" = "1.0.0.9" 4 | "ENLISTMENT_CHOICE" = "NEVER" 5 | "PROJECT_FILE_RELATIVE_PATH" = "" 6 | "NUMBER_OF_EXCLUDED_FILES" = "0" 7 | "ORIGINAL_PROJECT_FILE_PATH" = "" 8 | "NUMBER_OF_NESTED_PROJECTS" = "0" 9 | "SOURCE_CONTROL_SETTINGS_PROVIDER" = "PROVIDER" 10 | } 11 | -------------------------------------------------------------------------------- /sharpAHK.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.28803.452 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "sharpAHK", "sharpAHK.csproj", "{2869DBFE-7762-4930-95EA-2B0C111CF353}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Debug|x64 = Debug|x64 12 | Debug|x86 = Debug|x86 13 | Release|Any CPU = Release|Any CPU 14 | Release|x64 = Release|x64 15 | Release|x86 = Release|x86 16 | EndGlobalSection 17 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 18 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Debug|x64.ActiveCfg = Debug|x64 21 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Debug|x64.Build.0 = Debug|x64 22 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Debug|x86.ActiveCfg = Debug|x86 23 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Debug|x86.Build.0 = Debug|x86 24 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Release|Any CPU.ActiveCfg = Release|Any CPU 25 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Release|Any CPU.Build.0 = Release|Any CPU 26 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Release|x64.ActiveCfg = Release|x64 27 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Release|x64.Build.0 = Release|x64 28 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Release|x86.ActiveCfg = Release|x86 29 | {2869DBFE-7762-4930-95EA-2B0C111CF353}.Release|x86.Build.0 = Release|x86 30 | EndGlobalSection 31 | GlobalSection(SolutionProperties) = preSolution 32 | HideSolutionNode = FALSE 33 | EndGlobalSection 34 | GlobalSection(ExtensibilityGlobals) = postSolution 35 | SolutionGuid = {E5FCCF97-28EB-446C-9093-A8CDD1E05A2C} 36 | EndGlobalSection 37 | EndGlobal 38 | -------------------------------------------------------------------------------- /sharpAHK.sln.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | sharpAHK 5 | LucidMethod 6 | 1.0.0.8 7 | LucidMethod 8 | https://github.com/LucidMethod 9 | https://github.com/LucidMethod 10 | https://github.com/LucidMethod/icon.ico 11 | false 12 | AutoHotkey for C# 13 | SharpAHK Release 14 | Copyright 2019 15 | sharpAHK AutoHotkey 16 | 17 | 18 | 19 | 20 | --------------------------------------------------------------------------------