How can I use an Image List to draw C# dragging outside of my own windows

北城以北 提交于 2019-12-25 14:21:10

问题


I am using C#'s inbuilt drag and drop via Control.DoDragDrop(). I use an Image List and ImageList_DragMove and friends to move a semi-transparent image around, tracking with the mouse. (See my reply in this thread for more information). How can I make the ImageList track the mouse when it is outside my windows? I only receive mouse position messages in OnDragOver(), and only when the mouse is over one of my Windows. The drag is going to another instance of my application, and I would like the ImageList to go the whole way, including over the desktop. I guess the basic problem is that DoDragDrop runs its own little message loop.

Windows Explorer gets this done so I know it is possible. I suppose I could start a thread to keep track of the mouse or write my own drag/drop message loop, but I am hoping for an easier way.


回答1:


You cannot draw outside your own windows. The way to do this is by changing the mouse cursor. That's what the GiveFeedback event is available, set e.UseDefaultCursors to false and set the Cursor.Current.

Just to give you an idea what this looks like, here's a sample form that drags visible text. Alter it to draw the bitmap the way you want it, from your ImageList for example. Beware that Bitmap.GetHicon() does not create great icons, the color mapping is poor.

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.GiveFeedback += Form1_GiveFeedback;
    }

    void Form1_GiveFeedback(object sender, GiveFeedbackEventArgs e) {
        string txt = "Dragging text";
        SizeF sz;
        using (var gr = this.CreateGraphics()) {
            sz = gr.MeasureString(txt, this.Font);
        }
        using (var bmp = new Bitmap((int)sz.Width, (int)sz.Height)) {
            using (var gr = Graphics.FromImage(bmp)) {
                gr.Clear(Color.White);
                gr.DrawString(txt, this.Font, Brushes.Black, 0, 0);
            }
            bmp.MakeTransparent(Color.White);
            e.UseDefaultCursors = false;
            IntPtr hIcon = bmp.GetHicon();
            Cursor.Current = new Cursor(hIcon);
            DestroyIcon(hIcon);
        }
    }
    protected override void OnMouseDown(MouseEventArgs e) {
        this.DoDragDrop("example", DragDropEffects.Copy);
    }
    [System.Runtime.InteropServices.DllImport("user32.dll")]
    extern static bool DestroyIcon(IntPtr handle);

}



回答2:


I suggest that you create a special form and drag it instead of using an ImageList. We have done this in our products (for example, XtraGrid) to allow the end-user arrange columns.



来源:https://stackoverflow.com/questions/3665196/how-can-i-use-an-image-list-to-draw-c-sharp-dragging-outside-of-my-own-windows

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