繁体   English   中英

如何在c#中将位图的IntPtr传递给CreateCaret

[英]How can I get the IntPtr of the bitmap to pass to CreateCaret in c#

我有以下代码

Bitmap Bmp=new Bitmap( nWidth, nHeight );
using ( Graphics gfx=Graphics.FromImage( Bmp ) ) {
    using ( SolidBrush brush=new SolidBrush( ForeColor ) ) {
        gfx.FillRectangle( brush, 0, 0, nWidth, nHeight );
    }
    Bmp = new Bitmap(nWidth, nHeight, gfx);
    CreateCaret( base.Handle, Bmp, nWidth, nHeight );
}

ShowCaret( base.Handle );

我遇到的问题是在这条线上:

CreateCaret( base.Handle, Bmp, nWidth, nHeight );

...因为它期望 Bmp 是 IntPtr

这个概念我试图以不需要从文件或资源加载位图的方式来做到这一点,但更多的是动态创建的。 我知道我可以通过IntPtr.Zero并且它会创建一个克拉,但是如果我这样做的话颜色会IntPtr.Zero

如何将创建的位图传递给CreateCaret方法?

传递位图的最简单方法是获取位图的句柄。 Microsoft 为Bitmap类型提供了GetHbitmap()扩展。

这可以按如下方式完成:

Bitmap bmp = new Bitmap( 800, 600 );  // create a new bitmap 800x600
IntPtr ptr = bmp.GetHbitmap(); // get the IntPtr handle

使用我的问题中的上述示例,可以这样处理插入符号的创建:

CreateCaret( base.Handle,  bmp.GetHbitMap(),  hWidth,  hHeight );

结果如下:

// Set the Caret color
Color CaretColor = Color.White;

// Invert the Caret color (ineffective)
Color invertedCaretColor=Color.FromArgb( CaretColor.ToArgb()^0xffffff );

// Get the character size
int nHeight = Convert.ToInt32(gfx.MeasureString("Z", base.Font).Height); // set the height to full character height
int nWidth = Convert.ToInt32(gfx.MeasureString("Z", base.Font).Width); // set the width to full character width

if ( nWidth>0&&nHeight>0 ) {
    // initialize bitmap
    using ( Bitmap bmp=new Bitmap( nWidth, nHeight ) ) {

        // initialize graphics
        using ( Graphics gfx=Graphics.FromImage( bmp ) ) {
            nWidth = Convert.ToInt32(gfx.MeasureString("Z", base.Font).Width * .66); // set the width to 2/3 character width

            // initialize brush for drawing background
            using ( SolidBrush brush=new SolidBrush( invertedCaretColor ) ) {
                gfx.FillRectangle( brush, 1, 1, nWidth, nHeight ); // draw offset by 1 pixel

                // initialize final bitmap for output as Caret
                using ( Bitmap bmp2=new Bitmap( nWidth, nHeight, gfx ) ) {

                    // Draw the Caret;

                    CreateCaret( base.Handle, bmp2.GetHbitmap(), nWidth, nHeight );
                    ShowCaret( base.Handle );
                }
            }
        }
    }
}

注意插入符号颜色总是根据背景颜色计算的。 这可以修改,但这里的文档只给出了一个可能的概念的粗略概念: How To Control the Caret Color

该文件对这个概念有这样的说法:

要将插入符号的颜色更改为黑色或白色以外的其他颜色需要做更多的工作,但结果的可靠性要低得多,因为应用程序必须解决以下等式:

 NOT(caret XOR background) = desired_color on the
                             "blink" of the caret.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM