![](/img/trans.png)
[英]InvalidOperationException: The Undo operation encountered a context that is different from what was applied in the corresponding Set operation
[英]When using SendKeys()-InvalidOperationException: Undo Operation encountered
這是我的代碼
public void KeyPress()
{
//Finds the target window and sends a key command to the application
Process[] processes = Process.GetProcessesByName("calc");
IntPtr calculatorHandle;
foreach (Process proc in processes)
{
calculatorHandle = proc.MainWindowHandle;
if (calculatorHandle == IntPtr.Zero)
{
MessageBox.Show("Calculator is not running.");
return;
}
SetForegroundWindow(calculatorHandle);
break;
}
SendKeys.SendWait("1");
}
執行此代碼后,我收到一個錯誤,我知道源是SendKeys。
這是我收到的完整錯誤
System.InvalidOperationException was unhandled
Message="The Undo operation encountered a context that is different from what was applied in the corresponding Set operation. The possible cause is that a context was Set on the thread and not reverted(undone)."
Source="mscorlib"
StackTrace:
at System.Threading.SynchronizationContextSwitcher.Undo()
at System.Threading.ExecutionContextSwitcher.Undo()
at System.Threading.ExecutionContext.runFinallyCode(Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteBackoutCodeHelper(Object backoutCode, Object userData, Boolean exceptionThrown)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Net.ContextAwareResult.Complete(IntPtr userToken)
at System.Net.LazyAsyncResult.ProtectedInvokeCallback(Object result, IntPtr userToken)
at System.Net.Sockets.BaseOverlappedAsyncResult.CompletionPortCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* nativeOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:
我不確定是什么問題,該數字會出現在我的計算器中,但會彈出該錯誤
好的,根據您對我的問題的回答,我將做出2個假設。
您正在從異步執行的函數(可能是從BeginReceive的回調或類似函數)中調用KeyPress。
您的應用程序是Windows窗體應用程序。
如果上述假設是正確的,那么我懷疑問題出在內部使用Windows消息傳遞的SendKeys,並且由於從UI線程以外的其他線程發送SendkKeys消息而出現了問題。 如果正確,則可以使用Control.Invoke來調用KeyPress函數來解決問題。 使用Control.Invoke
將封送回UI線程的調用。
我自己玩過這個游戲,無法復制。
做了一次Google搜索,發現下面的文章有很多建議,您可能想嘗試一下。 http://social.msdn.microsoft.com/forums/en-US/netfxbcl/thread/48b4a763-7387-46da-8fc2-3e885670f62c
當然,您可能已經看過那里,所以才來到這里。
您可能需要提供有關調用代碼上下文的更廣泛的信息。 該應用程序的用途是什么? 您能告訴它哪一行代碼失敗嗎?
另外,正如@SLaks建議的那樣,您可以包括內部異常的更多詳細信息嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.