模拟CTRL,直到我想要c#?

时间:2018-01-23 02:37:32

标签: c# datagridview

我试图模拟用户按下按下ctrl,主要目标是在数据网格视图中,当我选择某些东西时(最初)我不希望用户然后更改该选择,如果不只是添加到它或者减去,就像你按住ctrl +鼠标左键一样。我不知道从哪里开始。我尝试创建一个与逻辑相结合的选择更改事件,但这将导致无限循环,因为我们将由用户选择一个,然后代码更改其他和其他等无限触发该事件。请帮助,我对编码有点新意。我也不知道如何确定是否按下了一个按键,按下并保持按下。

        private void selecttionh(object sender, EventArgs e)
    {

        if (stage == "4A" || stage == "3B" && ModifierKeys.HasFlag(Keys.Control))
        {
            int nothing = 0;
            btnclickercl bt = new btnclickercl();
            bt.dataGridView1_SelectionChanged(sender, e, dataGridViewReslist, dataGridViewnewres, nothing);
        }
        if (stage == "4A" || stage == "3B" && (ModifierKeys & Keys.Control) != Keys.Control)
        {
            MessageBox.Show("Please Press and hold " + "'ctrl'" + " to continue");
            dataGridViewReslist.ClearSelection();
            for (int i = 0; i < ResRoomSelections.Count; i++)
            {
                dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
                dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
            }
        }
        else
        {
                dataGridViewReslist.ClearSelection();
                for (int i = 0; i < ResRoomSelections.Count; i++)
                {
                    dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[ResRoomSelections[i][1]].Selected = true;
                    dataGridViewReslist.Rows[ResRoomSelections[i][0]].Cells[(ResRoomSelections[i][1]) + 1].Selected = true;
                }
        }  

    }

2 个答案:

答案 0 :(得分:0)

实现此目的的方法是单独存储选择状态,在用户单击单元格时更新它,然后重新应用它。这可以防止每次点击时选择丢失。如果您挂钩正确的事件处理程序(鼠标,而不是单击),您可以在没有屏幕闪烁的情况下执行此操作,否则看起来很乱。

您需要的所有内容都在此课程中,包括扩展方法static public class Example { static private bool[][] GetSelectionState(DataGridView input) { int rowCount = input.Rows.Count; int columnCount = input.Columns.Count; var result = new bool[rowCount][]; for (var r = 0; r < rowCount; r++) { result[r] = new bool[columnCount]; for (var c = 0; c < columnCount; c++) { var cell = input.Rows[r].Cells[c]; result[r][c] = cell.Selected; } } return result; } static private void SetSelectionState(DataGridView input, bool[][] selectionState) { for (int r = 0; r <= selectionState.GetUpperBound(0); r++) { for (int c = 0; c <= selectionState[r].GetUpperBound(0); c++) { input.Rows[r].Cells[c].Selected = selectionState[r][c]; } } } static public void SetupToggledSelectionMode(this DataGridView input) { bool[][] selectionState = GetSelectionState(input); //This will be stored in a closure due to the lambda expressions below input.CellMouseUp += (object sender, DataGridViewCellMouseEventArgs e) => { selectionState[e.RowIndex][e.ColumnIndex] = !selectionState[e.RowIndex][e.ColumnIndex]; SetSelectionState(input, selectionState); }; input.SelectionChanged += (object sender, EventArgs e) => { if (selectionState != null) { SetSelectionState(input, selectionState); } }; } } ,这是您的切入点。

myDataGrid.DataSource = myData;
myDataGrid.Refresh();
myDataGrid.SelectAll();
myDataGrid.SetupToggledSelectionMode();

要使用,请填充gridview,以编程方式设置初始选择,并按以下方式调用:

SetupToggledSelectionMode()

var unparsedXml:String? public func getTrackingInfo(_ trackingNumber: String) -> TrackingInfo { let group = DispatchGroup() group.enter() DispatchQueue.global(qos: DispatchQoS.default.qosClass).async { self.callRestService(requestUrl: self.getRequest(trackingNumber)) group.leave() } group.wait() print(unparsedXml) return TrackingInfo() } private func getRequest(_ trackingNumber: String) -> String { let APIUsername = "Intentionally Omitted" let trackingXmlLink = "http://production.shippingapis.com/ShippingAPI.dll?API=TrackV2&XML=%3CTrackFieldRequest%20USERID=%22" + APIUsername + "%22%3E%20%3CRevision%3E1%3C/Revision%3E%20%3CClientIp%3E127.0.0.1%3C/ClientIp%3E%20%3CSourceId%3EFaiz%20Surani%3C/SourceId%3E%20%3CTrackID%20ID=%22" + trackingNumber + "%22%3E%20%3CDestinationZipCode%3E66666%3C/DestinationZipCode%3E%20%3CMailingDate%3E2010-01-01%3C/MailingDate%3E%20%3C/TrackID%3E%20%3C/TrackFieldRequest%3E" return trackingXmlLink } public func callRestService(requestUrl:String) ->Void { var request = URLRequest(url: URL(string: requestUrl)!) request.httpMethod = "GET" let session = URLSession.shared let task = session.dataTask(with: request, completionHandler: serviceCallback) task.resume() } private func serviceCallback(data:Data? , response:URLResponse? , error:Error? ) -> Void { unparsedXml = String(data: data!, encoding: .utf8) //print(unparsedXml) Works correctly when uncommented } 方法将注册必要的事件处理程序,并将网格的选择状态存储在两个处理程序都可访问的已关闭变量中。所以你不必另外申报任何东西;只需调用方法。

答案 1 :(得分:0)

谢谢你,这对我很有帮助。我所做的只是为了让它更有效率。因为它会调用Selection的每一步,所以我完全摆脱了那个事件,只保留了CellMouseup事件。

static private bool[][] GetSelectionState(DataGridView input)
{
    int rowCount = input.Rows.Count;
    int columnCount = input.Columns.Count;
    var result = new List<int[]>();
    for (var r = 0; r < rowCount; r++)
    {
        for (var c = 0; c < columnCount; c++)
        {
            if(input.Rows[r].Cells[c].Selected==true)
           {
            result.add(new int[]{r,c});//will keep only the integer of selected items
           }
        }
    }
    return result;//this for me was a recycled variable it can be used or recycled from somewhere else
}

private void SetSelectionState(DataGridView input,result)
    {
        for (int i=0;i<result.Count;i++)
        {
            input.Rows[result[i][0]].Cells[result[i][1]].Selected = true;

        }
    }
public void SetupToggledSelectionMode(DataGridView input,result)
    {
     for (int i=0;i<result.Count;i++)
            {
                if(result[i].SequenceEqual(new int[] { e.RowIndex, e.ColumnIndex }))
                {
                    result.RemoveAt(i);
                    continueer = 1;
                    break;
                }
            }
            if (continueer == 0)
            {
                ResRoomSelections.Add(new int[] { e.RowIndex, e.ColumnIndex });
            }
        SetSelectionState(input);
         //whatever else you need to do 
 }

我知道搜索List还有更好的方法,但我无法进行lamda搜索,所以我只是使用暴力

- 谢谢John Wu所有