这实际上被称为caret,而不是一个cursor。这可能就是混乱的根源,也是为什么寻找解决方案没有产生太多用处的原因。NullPonyPointer 的评论 https://stackoverflow.com/questions/13439717/how-to-change-windows-blink-cursor-shape-from-c#comment18373963_13439717也反映了这种常见的困惑。这SetCursor
函数确实是您想要更改鼠标光标的函数,但更改插入符号不起作用。
幸运的是,有一整组 Windows 函数可以使用插入符:CreateCaret http://msdn.microsoft.com/en-us/library/windows/desktop/ms648399.aspx, ShowCaret http://msdn.microsoft.com/en-us/library/windows/desktop/ms648406.aspx, HideCaret http://msdn.microsoft.com/en-us/library/windows/desktop/ms648403.aspx, SetCaretPos http://msdn.microsoft.com/en-us/library/windows/desktop/ms648405.aspx, and DestroyCaret http://msdn.microsoft.com/en-us/library/windows/desktop/ms648400.aspx。还有其他一些用于操纵眨眼时间的方法,但我建议坚持用户当前的设置(这将是默认设置)。
首先,介绍一些背景知识。我强烈建议阅读两篇 MSDN 介绍性文章关于插入符 http://msdn.microsoft.com/en-us/library/windows/desktop/ms648397.aspx and on 使用插入符 http://msdn.microsoft.com/en-us/library/windows/desktop/ms648398.aspx。但这里有一个简单的总结:插入符号由窗口拥有;特别是当前具有焦点的窗口。该窗口可能类似于文本框控件。当窗口接收焦点时,它会创建一个插入符号以供使用,然后当它失去焦点时,它会销毁其插入符号。显然,如果您不手动执行任何操作,您将收到默认实现。
现在,示例代码。因为我喜欢糖果机界面,所以我将它包装在一个函数中:
bool CreateCustomCaret(HWND hWnd, int width, int height, int x, int y)
{
// Create the caret for the control receiving the focus.
if (!CreateCaret(hWnd, /* handle to the window that will own the caret */
NULL, /* create a solid caret using specified size */
width, /* width of caret, in logical units */
height)) /* height of caret, in logical units */
return false;
// Set the position of the caret in the window.
if (!SetCaretPos(x, y))
return false;
// Show the caret. It will begin flashing automatically.
if (!ShowCaret(hWnd))
return false;
return true;
}
然后,响应WM_SETFOCUS http://msdn.microsoft.com/en-us/library/windows/desktop/ms646283.aspx, EN_SETFOCUS http://msdn.microsoft.com/en-us/library/windows/desktop/bb761685.aspx,或类似的通知,我会打电话给CreateCustomCaret
功能。并回应WM_KILLFOCUS http://msdn.microsoft.com/en-us/library/windows/desktop/ms646282.aspx, EN_KILLFOCUS http://msdn.microsoft.com/en-us/library/windows/desktop/bb761682.aspx,或其他类似的通知,我会打电话DestroyCaret()
.
或者,CreateCustomCaret
可以从位图创建插入符号。我可能会提供以下重载:
bool CreateCustomCaret(HWND hWnd, HBITMAP hbmp, int x, int y)
{
// Create the caret for the control receiving the focus.
if (!CreateCaret(hWnd, /* handle to the window that will own the caret */
hBmp, /* create a caret using specified bitmap */
0, 0)) /* width and height parameters ignored for bitmap */
return false;
// Set the position of the caret in the window.
if (!SetCaretPos(x, y))
return false;
// Show the caret. It will begin flashing automatically.
if (!ShowCaret(hWnd))
return false;
return true;
}