[英]How to return all of the data in a COLORREF to the caller in C#
I'm trying to write a .dll
and then call this .dll
in C#.我正在尝试编写一个.dll
,然后在C#中调用这个.dll
。 I followed this article:我关注了这篇文章:
https://blog.quickbird.uk/calling-c-from-net-core-759563bab75d https://blog.quickbird.uk/calling-c-from-net-core-759563bab75d
Now, I have the problem of how to return all of the data in a COLORREF
to the caller in C#, and then to be able to distinguish the values.现在,我遇到的问题是如何将COLORREF
中的所有数据返回给 C# 中的调用者,然后才能区分这些值。
This is the source from the .dll
:这是来自.dll
的来源:
#pragma once
#include <windows.h>
extern "C"
{
__declspec(dllexport) COLORREF __stdcall getColor(int X, int Y) {
HDC _hdc = GetDC(NULL);
COLORREF _result = 0;
if (_hdc)
{
_result = GetPixel(_hdc, X, Y);
/* int _red = GetRValue(_result);
int _green = GetGValue(_result);
int _blue = GetBValue(_result); */
ReleaseDC(NULL, _hdc);
return _result;
}
return _result;
}
}
And here are some parts from the C# source:以下是 C# 源代码中的一些部分:
public partial class Main_Window : Form
{
[DllImport(@"test.dll", EntryPoint = "getColor", CallingConvention = CallingConvention.StdCall)]
private static extern UInt32 getColor(int X, int Y);
private void ColB_Click(object sender, EventArgs e)
{
UInt32 result = getColor(500, 500);
MessageBox.Show(Convert.ToString(result)); //<--- just to show what pops up.
//ColB.BackColor = result; //<--- that didnt work.
}
}
COLORREF
is just an alias for DWORD
, which is indeed UInt32
in C#. COLORREF
只是DWORD
的别名,在 C# 中确实是UInt32
。 So, your code looks fine, as far as calling your getColor()
function in C#.因此,您的代码看起来不错,只要在 C# 中调用您的getColor()
function。 Though, I would suggest making the function return CLR_INVALID
( 0xFFFFFFFF
) on failure rather than returning 0 (Black), especially since GetPixel()
returns CLR_INVALID
on failure, eg:不过,我建议让 function 在失败时返回CLR_INVALID
( 0xFFFFFFFF
) 而不是返回 0 (Black),特别是因为GetPixel()
在失败时返回CLR_INVALID
,例如:
COLORREF __stdcall getColor(int X, int Y) {
COLORREF _result = CLR_INVALID;
HDC _hdc = GetDC(NULL);
if (_hdc)
{
_result = GetPixel(_hdc, X, Y);
ReleaseDC(NULL, _hdc);
}
return _result;
}
That being said, the BackColor
property of a control expects a System.Drawing.Color
, not a UInt32
.话虽如此,控件的BackColor
属性需要System.Drawing.Color
,而不是UInt32
。 You can get a Color
from a COLORREF
by using one of the Color.FromArgb()
methods, eg:您可以使用Color.FromArgb()
方法之一从COLORREF
获取Color
,例如:
UInt32 result = getColor(500, 500);
if (result != 0xFFFFFFFF) {
int red = (int) (byte) (result & 0xFF);
int green = (int) (byte) ((result >> 8) & 0xFF);
int blue = (int) (byte) ((result >> 16) & 0xFF);
ColB.BackColor = Color.FromArgb(red, green, blue);
}
Or, the System.Drawing.ColorTranslator.FromWin32()
method:或者, System.Drawing.ColorTranslator.FromWin32()
方法:
UInt32 result = getColor(500, 500);
if (result != 0xFFFFFFFF) {
ColB.BackColor = ColorTranslator.FromWin32( (int) result );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.