我试图在.Net Core 2.0中使用PostThreadMessage和GetMessage,但它失败了。
这是我的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
[DllImport("user32.dll")]
public static extern int GetMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PeekMessage(out MSG lpMsg, IntPtr hWnd, uint wMsgFilterMin, uint wMsgFilterMax, uint wRemoveMsg);
[DllImport("user32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool PostThreadMessage(uint threadId, uint msg, UIntPtr wParam, IntPtr lParam);
[DllImport("Kernel32.dll", SetLastError = true)]
public static extern Int32 GetLastError();
[StructLayout(LayoutKind.Sequential)]
public struct MSG
{
public IntPtr hwnd;
public uint message;
public IntPtr wParam;
public IntPtr lParam;
public uint time;
}
private static uint threadId = 0;
static void Main(string[] args)
{
var mMsgThread = new Thread(MyThread);
mMsgThread.Priority = ThreadPriority.Highest;
mMsgThread.Start();
Thread.Sleep(100);
bool status = PostThreadMessage(threadId, 0, UIntPtr.Zero, IntPtr.Zero);
Int32 err = GetLastError();
}
private static void MyThread(object obj)
{
#pragma warning disable CS0618 // Type or member is obsolete
threadId = (uint)AppDomain.GetCurrentThreadId();
#pragma warning restore CS0618 // Type or member is obsolete
MSG Msg = new MSG();
var RetVal = GetMessage(out Msg, IntPtr.Zero, 0, 0);
Console.WriteLine(RetVal);
}
}
}
我弄错了#39;来自PostThreadMessage,GetLastError()返回0(而不是真正的错误)。
此代码在.Net Framework上正常运行
如何在.Net Core 2.0上运行它?