Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
649 views
in Technique[技术] by (71.8m points)

c# - Invoke delegate on main thread in console application

In a Windows Application, when multiple threads are used, I know that it’s necessary to invoke the main thread to update GUI components. How is this done in a Console Application?

For example, I have two threads, a main and a secondary thread. The secondary thread is always listening for a global hotkey; when it is pressed the secondary thread executes an event that reaches out to the win32 api method AnimateWindow. I am receiving an error because only the main thread is allowed to execute said function.

How can I effectively tell the main thread to execute that method, when "Invoke" is not available?


update: if it helps, here is the code. To see the HotKeyManager stuff(where the other thread is coming into play), check out the answer to this question
class Hud
{
    bool isHidden = false;
    int keyId;

    private static IntPtr windowHandle;

    public void Init(string[] args)
    {
        windowHandle = Process.GetCurrentProcess().MainWindowHandle;
        SetupHotkey();
        InitPowershell(args);
        Cleanup();
    }

    private void Cleanup()
    {
        HotKeyManager.UnregisterHotKey(keyId);
    }

    private void SetupHotkey()
    {

        keyId = HotKeyManager.RegisterHotKey(Keys.Oemtilde, KeyModifiers.Control);
        HotKeyManager.HotKeyPressed += new EventHandler<HotKeyEventArgs>(HotKeyManager_HotKeyPressed);
    }

    void HotKeyManager_HotKeyPressed(object sender, HotKeyEventArgs e)
    {
       ToggleWindow();
    }

    private void ToggleWindow()
    {
        //exception is thrown because a thread other than the one the console was created in is trying to call AnimateWindow

        if (isHidden)
        {
            if (!User32.AnimateWindow(windowHandle, 200, AnimateWindowFlags.AW_VER_NEGATIVE | AnimateWindowFlags.AW_SLIDE))
                throw new Win32Exception(Marshal.GetLastWin32Error());
        }
        else
        {
            if (!User32.AnimateWindow(windowHandle, 200, AnimateWindowFlags.AW_VER_POSITIVE | AnimateWindowFlags.AW_HIDE))
                throw new Win32Exception(Marshal.GetLastWin32Error());
        }
        isHidden = !isHidden;
    }

    private void InitPowershell(string[] args)
    {
        var config = RunspaceConfiguration.Create();
        ConsoleShell.Start(config, "", "", args);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the documentation on MSDN say :

The function will fail in the following situations:

  • [...]
  • If the thread does not own the window. [...]

So there is no "main" thread in question here (AFAIK Win32Api doesn't care about witch thread your program entry point is executed on).

The only condition is that you must execute AnimateWindow on a thread that is owning the window that you are animating. That's the one that called CreateWindow as it is the function that define the thread / message-loop afinity).

  • Most of the time as Jon said this thread should be running a message loop created by Application.Run.
    From another thread you could use the Control.Invoke method to force the main thread to execute code. If you don't have a Control reference, just create one while in the main thread and call it's CreateHandle method. If you have a main form just use it
  • The message loop could also be created the old school way, especially if you already create your window by PInvoke anyway. The main thread should have a standard PeekMessage loop waiting at least for WM_QUIT and a WM_EXECUTE_ANIMATE_WINDOW that you define. The secondary thread posing this message via PostMessage or PostThreadMessage.

Now that you have posted your sample code, the problem that you will have is that you aren't trying to animate just any window... but you are trying to animate the console window itself... And you aren't on it's owner thread (otherwise it won't refresh when you create an infinite loop in your application)... so calling AnimateWindow won't be possible except if you manage to coerce windows to execute code on that thread.

The fact console windows are in fact owned by CSRSS witch is a system process executing with elevated rights make messing with them really risky anyway.

Since windows vista it's even impossible to send a message to such windows due to process protection so any vulnerability that could be exploited previously to coerce this thread to execute code should now be unusable.

For the details regarding the specificity of the console window see the Why aren't console windows themed on Windows XP? post on the Raymond Chen blog (from the microsoft windows shell team so it's pretty much from the source)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...