public static bool AutoFocus(IVideoProvider provider, float maxPos, float minPos, float step = 0.2f) { try { if (provider == null) { return(false); } bool isCapture = provider.IsRunning; Dictionary <double, float> pos = new Dictionary <double, float>(); Z_Axis.AxisJogAbsWork(maxPos); if (!WaitAxisMoveDone()) { return(false); } if (!isCapture) { provider.StartCapture(); } int stepTick = (int)((maxPos - minPos) / step); double scalValue = 0; int tick = 0; for (int i = 0; i < stepTick; i++) { Z_Axis.AxisJogIncWork(-step, true); Thread.Sleep(20); Bitmap map = provider.GetCurrentFrame(); double qua = map.GetLinearQuality(); if (!pos.ContainsKey(qua)) { if (qua < scalValue) { if (tick++ > 3) { break; } } else { tick = 0; } scalValue = qua; pos.Add(qua, z_Axis.RealPos); } } double maxKey = pos.Max(r => r.Key); float desPos = pos[maxKey]; Z_Axis.AxisJogAbsWork(desPos); if (!isCapture) { provider.StopCapture(); } pos.Clear(); GC.Collect(); if (step / 20 < 0.005) { return(true); } else { return(AutoFocus(provider, desPos + step, desPos - step, step / 10)); } } catch { return(false); } }