Tooltip attached to mouse in C#

空扰寡人 提交于 2019-12-12 11:19:31

问题


How do I get a tooltip that is attached to the mouse cursor using C#? I'm trying to achieve an effect like the following, a small tooltip showing the status of Ctrl / Shift / Alt keys.

I'm currently using a Tooltip but it refuses to display unless it has about 2 lines of text.

tt = new ToolTip();
tt.AutomaticDelay = 0;
tt.ShowAlways = true;
tt.SetToolTip(this, " ");

In mouse move:

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


回答1:


So I don't think there is any way you could do this purely with managed code. You would have to go native.

The way I see it there are two options.

  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


To get you upto speed, you would have something like this defined in you .NET code. I got the definition from here.

You will find all the structures I've mentioned in my answer on the same website (or other similar ones) Once you have defined all of them in your code, you can then easily transpose/port the C samples that are in my answer and the linked articles.:

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);
}


来源:https://stackoverflow.com/questions/11098468/tooltip-attached-to-mouse-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!