我尝试从C#代码调用WinAPI函数时出现问题。 我有很多的import,其中许多工作正常,但其中一些没有,并导致意外中断主程序,没有任何消息,exceptiontypes,没有什么,只是倒下了所有的窗口,并退出。
我有两种方法在代码中:通过我开发的库,哪里是更多的winapi调用,我懒编码特定的结构,指针等,并直接从user32.dll导入,如下所示:
[DllImport(@"tradeInterop.dll")] public static extern void ChooseInstrumentByMouse(UInt32 hwnd, int baseX, int baseY, int idx, int _isDown); [DllImport(@"tradeInterop.dll")] public static extern void PutNumber(int num); [DllImport(@"tradeInterop.dll")] public static extern void PutRefresh(); [DllImport(@"user32.dll")] public static extern UInt32 FindWindow(string sClass, string sWindow); [DllImport(@"user32.dll")] public static extern int GetWindowRect(uint hwnd, out RECT lpRect); [DllImport(@"user32.dll")] public static extern int SetWindowPos(uint hwnd, uint nouse, int x, int y, int cx, int cy, uint flags); [DllImport(@"user32.dll")] public static extern int LockSetForegroundWindow(uint uLockCode); [DllImport(@"user32.dll")] public static extern int SetForegroundWindow(uint hwnd); [DllImport(@"user32.dll")] public static extern int ShowWindow(uint hwnd, int cmdShow); [DllImport(@"tradeInterop.dll")] public static extern ulong PixelColor(uint hwnd, int winX, int winY); //tried (signed) long and both ints as return type, same result (WINAPI says DWORD as unsigned long, what about 64-bit assembly where compiled both lib and program? public struct RECT { public int Left; public int Top; ...
正如我所说,这些调用很多作品完美,但最后两个问题:ShowWindow()和PixelColor()与下面的代码:
extern "C" __declspec(dllexport) COLORREF __stdcall PixelColor(unsigned hwnd, int winX, int winY) { LPPOINT point; point->x = winX; point->y = winY; ClientToScreen((HWND) hwnd, point); HDC dc = GetDC(NULL); COLORREF colorPx = GetPixel(dc, point->x, point->y); ReleaseDC(NULL, dc); return colorPx; }
所以,当我尝试直接调用导入的ShowWindow()函数或调用api函数的函数库时,程序崩溃
有没有办法如何debugging外部库及其结果?
我做错了什么?
非常感谢
调试问题有几个选项。
WinDbg
。 这将是我个人最喜欢的调试混合应用程序的选项。 这是一个令人难以置信的强大工具。 不可否认的是,学习曲线有点陡峭,但是值得努力。 P /调用问题:
HWND
应该使用IntPtr
传递给非托管代码。 DWORD
总是32位。 另外, LONG
(全部大写)与long
(小写)不一样。 C ++问题:
LPPOINT
永远不会被初始化,所以当你调用ClientToScreen()
你正在访问未初始化的栈垃圾作为指针,并分配值。 要修复它,你可以:
LocalAlloc
, GlobalAlloc
, malloc
, calloc
。 POINT point;
,使用point.x
和point.y
分配值,并在函数调用中使用它作为&point
。 HWND
。 API类型尽管最终是typedef,但它们带有额外的含义。