我试图完成一项简单的任务,从另一个帖子更新表单中的进度条,经过4个多小时左右的googleing,我仍然无法掌握它...到目前为止,这是我的代码,我错了?任何人都能指出我正确的方向吗?
namespace ImageLoader
{
public partial class Form1 : Form
{
BackgroundWorker bgw = new BackgroundWorker();
public Form1()
{
InitializeComponent();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.ProgressChanged += new ProgressChangedEventHandler(bgw_ProgressChanged);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
bgw.WorkerReportsProgress = true;
}
private void button1_Click(object sender, EventArgs e)
{
bgw.RunWorkerAsync();
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
Excel.Worksheet activeWorksheet = ((Excel.Worksheet)Globals.ThisAddIn.Application.ActiveSheet);
bool test = false;
bool testStr = false;
int urlsColPos = 0;
int imgColPos = 0;
object result;
object result2;
result = textBox1.Text;
result2 = textBox2.Text;
string urlValidi = "http";
if (result == "" || result2 == "")
{
MessageBox.Show("Uno dei due campi non è stato valorizzato, compilare entrambi i campi prima di continuare.");
test = false;
}
else
{
urlsColPos = char.ToUpper(Convert.ToChar(result)) - 64;
imgColPos = char.ToUpper(Convert.ToChar(result2)) - 64;
var s1 = (activeWorksheet.Cells[2, urlsColPos] as Excel.Range).Value.ToString();
var s2 = (activeWorksheet.Cells[2, imgColPos] as Excel.Range).Value;
testStr = s1.Contains(urlValidi);
if (testStr == false)
{
MessageBox.Show("La colonna specificata per l'origine URLs non contiene URL validi");
}
if (s2 != null)
{
MessageBox.Show("La colonna dove inserire le immagini non è vuota");
}
if (testStr == true && s2 == null)
{
test = true;
}
}
if (test == true)
{
HttpWebResponse response = null;
Excel.Range range = activeWorksheet.UsedRange;
double lastRow = range.Rows.Count;
activeWorksheet.Rows.RowHeight = 62;
activeWorksheet.Columns.ColumnWidth = 12;
for (var i = 2; i <= lastRow; i++)
{
Application.DoEvents();
Microsoft.Office.Interop.Excel.Range oRange = (Microsoft.Office.Interop.Excel.Range)activeWorksheet.Cells[i, imgColPos];
//const float ImageSize = 45;
float Left = (float)((double)oRange.Left + 2);
float Top = (float)((double)oRange.Top + 1);
var imgUrl = (string)(activeWorksheet.Cells[i, urlsColPos] as Excel.Range).Value;
int ultimaRiga = (int)lastRow;
int percents = (i * 100) / ultimaRiga;
//progressBar1.Step = 1;
//progressBar1.Value = i;
bgw.ReportProgress(percents, i);
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(imgUrl);
request.Method = "GET";
response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
byte[] imgData = new WebClient().DownloadData(imgUrl);
MemoryStream imgStream = new MemoryStream(imgData);
Image img = Image.FromStream(imgStream);
float wSize = img.Width;
float hSize = img.Height;
if (hSize > wSize) //Verticale
{
activeWorksheet.Shapes.AddPicture(imgUrl, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left + 14, Top, 40, 60);
}
else
{
activeWorksheet.Shapes.AddPicture(imgUrl, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue, Left + 3, Top + 10, 60, 40);
}
Application.DoEvents();
//Console.Write(sr.ReadToEnd());
}
catch (WebException f)
{
activeWorksheet.Cells[i, 10] = "Errore Server Remoto Nuxie";
}
finally
{
response.Close();
}
}
this.Close();
}
}
void bgw_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
return;
}
}
}
答案 0 :(得分:0)
显然有一些错误可能会产生交叉线程问题。
例如,您不需要使用package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
// import br.com.simplepass.loading_button_lib.customViews.CircularProgressButton;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText)findViewById(R.id.loginEmail);
loginSenha = (EditText)findViewById(R.id.loginSenha);
btLogar = (Button)findViewById(R.id.btLogar);
refCadastrar = (TextView)findViewById(R.id.refCadastrar);
refCadastrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
btLogar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if(email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.100/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
} else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
@Override
protected void onPostExecute(String resultado) {
if(resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[1]);
abreHome.putExtra("nomeusu", dados[2]);
startActivity(abreHome);
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
@Override
protected void onPause() {
super.onPause();
finish();
}
}
,因为您使用的是Application.DoEvents()
,因此当您在{{1}处设置值时,进度条会自动刷新方法。
而且你也不需要&#34;计算&#34;百分比,如行:
BackgroundWorker
如果您只是设置进度条bgw_ProgressChanged
并在int percents = (i * 100) / ultimaRiga;
之后,Windows窗体将自动计算百分比,并在进度条中正确设置进度。
在你的代码中你可以这样做:
Maximum