|
1 |
| -#nullable enable |
| 1 | +#nullable enable |
2 | 2 |
|
3 | 3 | using System;
|
4 | 4 | using System.IO;
|
5 | 5 | using System.Text.Json;
|
6 | 6 | using System.Text.Json.Serialization;
|
| 7 | +using System.Diagnostics; |
| 8 | +using System.Runtime.InteropServices; |
| 9 | +using System.Linq; |
| 10 | +using System.Collections.Generic; |
| 11 | +using win32api = Microsoft.Win32; |
7 | 12 |
|
8 | 13 | namespace Flow.Launcher.Infrastructure
|
9 | 14 | {
|
@@ -86,5 +91,41 @@ public static string Formatted<T>(this T t)
|
86 | 91 |
|
87 | 92 | return formatted;
|
88 | 93 | }
|
| 94 | + |
| 95 | + public static string GetActiveOfficeFilePath() |
| 96 | + { |
| 97 | + var pid = GetActiveWindowProcessId(); |
| 98 | + var handle = win32api.OpenProcess(win32api.PROCESS_QUERY_INFORMATION | win32api.PROCESS_VM_READ, false, pid); |
| 99 | + var exePath = win32api.GetModuleFileNameEx(handle, 0); |
| 100 | + if (exePath.ToLower().Contains("winword.exe")) |
| 101 | + { |
| 102 | + return Path.GetFullPath(new win32api.Dispatch("Word.Application").ActiveDocument.FullName); |
| 103 | + } |
| 104 | + else if (exePath.ToLower().Contains("powerpnt.exe")) |
| 105 | + { |
| 106 | + return Path.GetFullPath(new win32api.Dispatch("PowerPoint.Application").ActivePresentation.FullName); |
| 107 | + } |
| 108 | + else if (exePath.ToLower().Contains("excel.exe")) |
| 109 | + { |
| 110 | + return Path.GetFullPath(new win32api.Dispatch("Excel.Application").ActiveWorkbook.FullName); |
| 111 | + } |
| 112 | + else |
| 113 | + { |
| 114 | + return null; |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + private static int GetActiveWindowProcessId() |
| 119 | + { |
| 120 | + var window = GetForegroundWindow(); |
| 121 | + var threadProcessId = GetWindowThreadProcessId(window, out var processId); |
| 122 | + return processId; |
| 123 | + } |
| 124 | + |
| 125 | + [DllImport("user32.dll")] |
| 126 | + private static extern IntPtr GetForegroundWindow(); |
| 127 | + |
| 128 | + [DllImport("user32.dll", SetLastError = true)] |
| 129 | + private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId); |
89 | 130 | }
|
90 | 131 | }
|
0 commit comments