C#中附加到鼠标的工具提示

4
我该如何使用C#实现一个附着在鼠标光标上的工具提示?我想要实现以下效果,即显示Ctrl / Shift / Alt键状态的小型工具提示。
我目前正在使用一个Tooltip,但它只有在有大约两行文本时才会显示。
tt = new ToolTip();
tt.AutomaticDelay = 0;
tt.ShowAlways = true;
tt.SetToolTip(this, " ");

鼠标移动时:

tt.ToolTipTitle = ".....";

tooltip


我已经添加了我的当前代码... - Robin Rodricks
1个回答

3

我认为没有纯粹使用托管代码的方法来实现这一点。你必须去使用本地代码。

在我看来,有两个选择:

  1. P/Invoke the SendMessage function. Set the hwnd to your target window and pass in a TTM_ADDTOOL message and a TOOLINFO structure for the lParam. This is useful when you want a tooltip on an external window you haven't created (one that isn't in your app). You could get its hwnd by calling FindWindow.

    See how all this is done here in this article. You just have to add the P/Invoke.

  2. Apparently you can use the CreateWindowEx() function with TOOLTIPS_CLASS as a classname and it will generate a tooltip for you. Something like this:

    HWND hwndTip = CreateWindowEx(NULL, TOOLTIPS_CLASS, NULL,
                            WS_POPUP | TTS_NOPREFIX | TTS_ALWAYSTIP,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            CW_USEDEFAULT, CW_USEDEFAULT,
                            hwndParent, NULL, hinstMyDll,
                            NULL);
    
    SetWindowPos(hwndTip, HWND_TOPMOST,0, 0, 0, 0,
             SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
    

    See the whole article here: http://msdn.microsoft.com/en-us/library/windows/desktop/bb760250(v=vs.85).aspx

为了让您了解情况,您的.NET代码中可能会定义类似于以下内容。我从这里获取了定义。
在同一网站(或其他类似网站)上可以找到我答案中提到的所有结构体。一旦您在代码中定义了它们,就可以轻松地转换/移植我的答案和链接文章中的C样例了。
class NativeFunctions 
{
[DllImport("user32.dll", SetLastError=true)]
static extern IntPtr CreateWindowEx(
   WindowStylesEx dwExStyle, 
   string lpClassName,
   string lpWindowName, 
   WindowStyles dwStyle, 
   int x, 
   int y, 
   int nWidth, 
   int nHeight,
   IntPtr hWndParent, 
   IntPtr hMenu, 
   IntPtr hInstance, 
   IntPtr lpParam);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接