C # эмулирует функцию перетаскивания по умолчанию в окнах (прозрачное изображение при перетаскивании) - PullRequest
0 голосов
/ 12 ноября 2018

У меня есть сетка данных с ячейками изображения (и скрытыми текстовыми ячейками), в которой я хочу иметь возможность перетаскивать изображения из одной ячейки в другую, в этой части я работаю, что я не могу заставить работать, это курсорво время перетаскивания.При перетаскивании я хотел бы, чтобы изображение заменяло курсор, аналогично тому, что происходит при перетаскивании файла на рабочий стол Windows.В настоящее время происходит то, что курсор мигает между пользовательским изображением, которое я хотел бы использовать, и курсором перетаскивания по умолчанию (указатель с маленьким прямоугольником).Я немного растерялся, как это исправить.Обратите внимание, что я не эксперт в кодировании, и большая часть моего кода составлена ​​из поиска в Google того, что я пытаюсь завершить, и объединения вещей.

GIF вопроса: https://gfycat.com/AgileImpressiveHermitcrab Обратите внимание, что мой рекордерне захватывает все, он мерцает намного быстрее, чем показано, и мерцает, когда мышь также не движется, без остановки (только при удерживании кнопки мыши)

    private DataGridViewCell drag_Image; //This is the initial image dragged
    private object HoldingImage;        //Stored target image
    private DataGridViewCell drag_ID;       //ID tied with initial image
    private object HoldingID;           //ID tied with stored target image
    private Bitmap DragCursor;  //This is the initial dragged image, set as the cursor
    private string DragIndicator;       //Attempting a new trigger for drag event

    private void dataGridView1_MouseMove(object sender, MouseEventArgs e)
    {//This code is not needed for functionality, what is the point here?

        //if ((e.Button & MouseButtons.Left) == MouseButtons.Left)
        {
            // If the mouse moves outside the rectangle, start the drag.
            //if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y))
            {

                // Proceed with the drag and drop, passing in the list item.                    
                //DragDropEffects dropEffect = dataGridView1.DoDragDrop(dataGridView1.Rows[dataGridView1.CurrentRow.Index],DragDropEffects.Move);
            }
        }
    }

    private void dataGridView1_DragOver(object sender, DragEventArgs e)
    {
       //This is where the cursor begins to flicker in the debugger, it cycles through this code
        Bitmap DragCursor = new Bitmap(@"C: \Users\******\Desktop\Items\Organizer\Planner\Planner\1.png");
        DragCursor.MakeTransparent(Color.White);

        Cursor cur = new Cursor(DragCursor.GetHicon());
        Cursor.Current = cur;

        e.Effect = DragDropEffects.Move;

        DragIndicator = "1";

    }

    private void dataGridView1_DragDrop(object sender, DragEventArgs e)
    {
        // The mouse locations are relative to the screen, so they must be 
        // converted to client coordinates.
        Point clientPoint = dataGridView1.PointToClient(new Point(e.X, e.Y));

        // Get the row index of the item the mouse is below. 
        DataGridView.HitTestInfo hti = dataGridView1.HitTest(clientPoint.X, clientPoint.Y);
        DataGridViewCell targetCell = dataGridView1[hti.ColumnIndex, hti.RowIndex];
        DataGridViewCell targetCellID = dataGridView1[hti.ColumnIndex + 1, hti.RowIndex];


        // If the drag operation was a move then remove and insert the row.
        //if (e.Effect == DragDropEffects.Move)
        if (DragIndicator == "1") //The new trigger works though we still can not removed all DragDropEffect.Move lines, as this disables dragging
        {
            if (SwapBtn.Enabled == false)
            {
                //Swap mode 
                HoldingImage = targetCell.Value;
                targetCell.Value = drag_Image.Value;
                drag_Image.Value = HoldingImage;

                HoldingID = targetCellID.Value;
                targetCellID.Value = drag_ID.Value;
                drag_ID.Value = HoldingID;
                dataGridView1.Refresh();
                DragIndicator = "0";
            }
            else
            {
                //TODO Insert mode

            }
        }
    }


    public void dataGridView1_MouseDown(object sender, MouseEventArgs e)
    {

        if (e.Button == System.Windows.Forms.MouseButtons.Left)
        {
            DataGridView.HitTestInfo hti = dataGridView1.HitTest(e.X, e.Y);
            drag_Image = dataGridView1[hti.ColumnIndex, hti.RowIndex];
            drag_ID = dataGridView1[hti.ColumnIndex + 1, hti.RowIndex];
            // Proceed with the drag and drop, passing in the list item.                    
            DragDropEffects dropEffect = dataGridView1.DoDragDrop(drag_Image, DragDropEffects.Move);
        }

    }

1 Ответ

0 голосов
/ 13 ноября 2018

Так что я не на 100% решил свою проблему, но я возьму ее. Решение изменить курсор и избежать мерцания, поскольку пользовательский курсор борется со значением по умолчанию ...

    private void dataGridView1_GiveFeedback(object sender, GiveFeedbackEventArgs e)
    {
        e.UseDefaultCursors = false;
    }

Нет стрелки на изображении, как в случае с функцией перетаскивания в Windows, но пока это работает.

...