Skip to content

Commit 97d2c7a

Browse files
authored
Merge pull request #129 from Code52/associated-process-fix
the process may not exist, and that's okay
2 parents f847af5 + 1d0dd84 commit 97d2c7a

File tree

1 file changed

+19
-10
lines changed

1 file changed

+19
-10
lines changed

src/Carnac.Logic/KeyProvider.cs

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ public IObservable<KeyPress> GetKeyStream()
7070
.Select(DetectWindowsKey)
7171
.Where(k => !IsModifierKeyPress(k) && k.KeyDirection == KeyDirection.Down)
7272
.Select(ToCarnacKeyPress)
73+
.Where(keypress => keypress != null)
7374
.Where(k => !passwordModeService.CheckPasswordMode(k.InterceptKeyEventArgs))
7475
.Subscribe(observer);
7576

@@ -98,6 +99,10 @@ bool IsModifierKeyPress(InterceptKeyEventArgs interceptKeyEventArgs)
9899
KeyPress ToCarnacKeyPress(InterceptKeyEventArgs interceptKeyEventArgs)
99100
{
100101
var process = GetAssociatedProcess();
102+
if (process == null)
103+
{
104+
return null;
105+
}
101106

102107
var isLetter = interceptKeyEventArgs.IsLetter();
103108
var inputs = ToInputs(isLetter, winKeyPressed, interceptKeyEventArgs).ToArray();
@@ -107,7 +112,7 @@ KeyPress ToCarnacKeyPress(InterceptKeyEventArgs interceptKeyEventArgs)
107112
ImageSource image = IconUtilities.GetProcessIconAsImageSource(processFileName);
108113
return new KeyPress(new ProcessInfo(process.ProcessName, image), interceptKeyEventArgs, winKeyPressed, inputs);
109114
}
110-
catch (System.Exception)
115+
catch (Exception)
111116
{
112117
return new KeyPress(new ProcessInfo(process.ProcessName), interceptKeyEventArgs, winKeyPressed, inputs); ;
113118
}
@@ -152,21 +157,25 @@ static IEnumerable<string> ToInputs(bool isLetter, bool isWinKeyPressed, Interce
152157

153158
Process GetAssociatedProcess()
154159
{
155-
Process process;
156-
157160
var handle = GetForegroundWindow();
158161

159-
if (!processes.ContainsKey(handle))
162+
if (processes.ContainsKey(handle))
163+
{
164+
return processes[handle];
165+
}
166+
167+
uint processId;
168+
GetWindowThreadProcessId(new IntPtr(handle), out processId);
169+
try
160170
{
161-
uint processId;
162-
GetWindowThreadProcessId(new IntPtr(handle), out processId);
163171
var p = Process.GetProcessById(Convert.ToInt32(processId));
164172
processes.Add(handle, p);
165-
process = p;
173+
return p;
174+
}
175+
catch (ArgumentException ex)
176+
{
177+
return null;
166178
}
167-
else
168-
process = processes[handle];
169-
return process;
170179
}
171180
}
172181
}

0 commit comments

Comments
 (0)