My code causes URL to open in 2 different tabs, why? - c#

As person helped me to figure out how to start open URL in default browser now I am having bit of a problem which causes to open URL in 2 different tabs when clicked. What could be the cause for this?
EDIT: I think it's good to point out that I am using a ListView in detailed mode. So when user clicks column with URL, it should open a single window in the browser.
lvWeb.MouseMove += new MouseEventHandler(lvWeb_MouseMove);
lvWeb.MouseUp +=new MouseEventHandler(lvWeb_MouseUp);
private void lvWeb_MouseMove(object sender, MouseEventArgs e)
{
var hit = lvWeb.HitTest(e.Location);
if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1])
lvWeb.Cursor = Cursors.Hand;
else lvWeb.Cursor = Cursors.Default;
}
private void lvWeb_MouseUp(object sender, MouseEventArgs e)
{
var hit = lvWeb.HitTest(e.Location);
if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1])
{
var url = new Uri(hit.SubItem.Text);
System.Diagnostics.Process.Start(url.ToString());
}
}

As one person sugested, I have visited the article which did the trick and it works as following:
private string getDefaultBrowser()
{
string browser = string.Empty;
RegistryKey key = null;
try
{
key = Registry.ClassesRoot.OpenSubKey(#"HTTP\shell\open\command", false);
//trim off quotes
browser = key.GetValue(null).ToString().ToLower().Replace("\"", "");
if (!browser.EndsWith("exe"))
{
//get rid of everything after the ".exe"
browser = browser.Substring(0, browser.LastIndexOf(".exe") + 4);
}
}
finally
{
if (key != null) key.Close();
}
return browser;
}
private void lvWeb_MouseUp(object sender, MouseEventArgs e)
{
var hit = lvWeb.HitTest(e.Location);
if (hit.SubItem != null && hit.SubItem == hit.Item.SubItems[1])
{
var url = new Uri(hit.SubItem.Text);
//System.Diagnostics.Process.Start(url.ToString());
Process p = new Process();
p.StartInfo.FileName = getDefaultBrowser();
p.StartInfo.Arguments = url.ToString();
p.Start();
}
}

Related

Combining Two buttons operation into single button in Visual Studio 2019 & C#

I have created a GUI in Visual Studio where I have two buttons. One button is used to show ip and second button is used to take that ip and run python script.
But I want to merge these both operations into only one button, that if clicked for the first time should show/take the ip, and when clicked a 2nd time, it should trigger the Python script and all that in single button click.
My code is:
private void button1_Click(object sender, EventArgs e)
{
var fileName = "C:\\test.txt";
var sr = new StreamReader(fileName);
string fileContent = sr.ReadToEnd();
var startBlock = "hello";
var endBlock = "exit";
var ip = ParseForIpRegex(fileContent, startBlock, endBlock);
myTextBox.Text = ip; //Change this to match your code
}
private readonly string IPV4_PATTERN = "[0-9.]";
private string ParseForIpRegex(string textToSearch, string startBlock, string endBlock)
{
var pattern = $#"{startBlock}\D*\s*({IPV4_PATTERN}+).*{endBlock}";
var ms = Regex.Match(textToSearch, pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase);
if (ms.Groups.Count > 0)
{
return ms.Groups[1].Value;
}
return string.Empty;
}
private void button1_Click_1(object sender, EventArgs e)
{
var hostname = myTextBox.Text;
var username = textBox1.Text;
var password = textBox2.Text;
var psi = new ProcessStartInfo();
psi.FileName = #"C:\Python38\python.exe";
var script = #"C:pythonscript.py";
//var config_file = file_path;
psi.Arguments = $"{script} {hostname} {username} {password}";
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
var errors = "";
var results = "";
MessageBox.Show("script processing");
using (var process = Process.Start(psi))
{
errors = process.StandardError.ReadToEnd();
results = process.StandardOutput.ReadToEnd();
}
Console.WriteLine("ERRORS:");
Console.WriteLine(errors);
Console.WriteLine();
Console.WriteLine("Results:");
Console.WriteLine(results);
if (errors != "")
{
MessageBox.Show(errors);
}
else
{
MessageBox.Show(results);
}
}
Please let me know how I can merge this both operation into one. That in one click 1st button operation will perform and after that 2nd in single click.
I suppose you need to keep all buttons, so you dont use args, just call the method:
private void button1_Click(object sender, EventArgs e)
{
//DO job
// simulate the second click
button1_Click_1(sender, e)
}
private void button1_Click_1(object sender, EventArgs e)
{
//you could test args to check if its coming from first button
}
The answer of Frenchy, or you can add 2 handers on the event...
depending your preference.
this.button1.Click += new System.EventHandler(this.button1_Click);
this.button1.Click += new System.EventHandler(this.button1_Click_1);
take note that one of the two the designer will add it for you.
So add the second at form_load event (or where u see fit)
Cheers

Google Places Autocomplete does not populate the address

I have an active Google Places autocomplete working with Xamarin Forms or Cross Platform. I have a working solution that auto populates the address when the user types in the address. My problem is when the user selects it from the list the address does not go to the search_bar.text… The search bar just remains with the text that was typed? how can I get the text when selected to populate in the search bar.
I am new to Xamarin forms and C#.
public Createbusinessaccount ()
{
InitializeComponent ();
search_bar.ApiKey = GooglePlacesApiKey;
search_bar.Type = PlaceType.Address;
search_bar.Components = new Components("country:us"); // Restrict results to Australia and New Zealand
search_bar.PlacesRetrieved += Search_Bar_PlacesRetrieved;
search_bar.TextChanged += Search_Bar_TextChanged;
search_bar.MinimumSearchText = 2;
results_list.ItemSelected += Results_List_ItemSelected;
}
void Search_Bar_PlacesRetrieved(object sender, AutoCompleteResult result)
{
results_list.ItemsSource = result.AutoCompletePlaces;
spinner.IsRunning = false;
spinner.IsVisible = false;
if (result.AutoCompletePlaces != null && result.AutoCompletePlaces.Count > 0)
results_list.IsVisible = true;
}
void Search_Bar_TextChanged(object sender, TextChangedEventArgs e)
{
if (!string.IsNullOrEmpty(e.NewTextValue))
{
results_list.IsVisible = false;
spinner.IsVisible = true;
spinner.IsRunning = true;
}
else
{
results_list.IsVisible = true;
spinner.IsRunning = false;
spinner.IsVisible = false;
}
}
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
In your ItemSelected method, you need to set the text of the searchbar:
async void Results_List_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
if (e.SelectedItem == null)
return;
var prediction = (AutoCompletePrediction)e.SelectedItem;
search_bar.Text = prediction.Name? // Your property here
results_list.SelectedItem = null;
var place = await Places.GetPlace(prediction.Place_ID, GooglePlacesApiKey);
if (place != null)
await DisplayAlert(
place.Name, string.Format("Lat: {0}\nLon: {1}", place.Latitude, place.Longitude), "OK");
}
I am still trying to fix this, it only adds the street name and number not the whole address

Extract a string from a webpage

i need to have a label where its text comes from a web page, but for somting it doesnt work out, it appearce to me that the webpae returned null, but the location is correct.
WebBrowser JOJO = new WebBrowser();
string Tesla = "";
JOJO.Url = new Uri("https://finance.yahoo.com/quote/TSLA?p=TSLA");
var sal = JOJO.Document.GetElementsByTagName("div");// this return null
foreach (HtmlElement link in sal)
{
if (link.GetAttribute("className") == "D(ib) Mend(20px)")/*this is the class of the element*/
{
Tesla = link.FirstChild.InnerHtml;
}
}
label11.Text = Tesla;
this is the code that i have done so far, can someone see why dosnt work?
Thanks.
It is null because it didn't load yet when you try to access it. You should be handling it asynchronously.
Handle the DocumentCompleted event and access the Document in the handler.
Replace the code you have with:
WebBrowser JOJO = new WebBrowser();
JOJO.DocumentCompleted += new System.Windows.Forms.WebBrowserDocumentCompletedEventHandler
(this.BrowserDocumentCompleted);
JOJO.Url = new Uri("https://finance.yahoo.com/quote/TSLA?p=TSLA");
And here is the handler:
void BrowserDocumentCompleted(object sender,
WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
return;
string Tesla = "";
var sal = (sender as WebBrowser).Document.GetElementsByTagName("div");
foreach (HtmlElement link in sal)
{
if (link.GetAttribute("className") == "D(ib) Mend(20px)")
{
Tesla = link.FirstChild.InnerHtml;
}
}
label1.Text = Tesla;
}
Now you will maybe face other problems with redirections. But that is another discussion :)

c# webbrowser viewer control takes time to dispose

When closing Form containing a WebBrowser control with a Pdf document open in the webbrowser, the form takes some 10 seconds to close. I tracked the issue down to Dispose method of the webbrowser.
private void advBandedGridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (advBandedGridView1.GetFocusedDataRow() != null)
{
string wordno = advBandedGridView1.GetFocusedDataRow()["wordno"].ToString();
string itemcd = advBandedGridView1.GetFocusedDataRow()["itemcd"].ToString();
for (int i = 0; i < _caseCount; i++)
{
ButtonColoring(wordno, _seqkindCode[i]);
}
LoadPDF(itemcd);
gridControl2.DataSource = null;
gridControl2.RefreshDataSource();
}
}
Control Event
private void LoadPDF(string itemcd)
{
try
{
ReturnPacket rp;
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = 'EYE'", false);
if (rp.DataTables.Count > 0 && rp.DataTables[0].Rows.Count == 0)
{
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = '1'", false);
}
if (rp.DataTables[0].Rows.Count > 0)
{
string dockind = string.Empty;
dockind = rp.DataTables[0].Rows[0]["code"].ToString();
ParameterCollection paramCol = new ParameterCollection();
paramCol.Add("p_itemcd", itemcd);
paramCol.Add("p_dockind", dockind);
PdfFileInfo temp_fileInfo = biz.SelectInspectionStandards(paramCol);
if (temp_fileInfo != null)
{
if (_fileInfo != null && temp_fileInfo.FileNm == _fileInfo.FileNm)
{
WebBrowserPdf.Visible = true;
return;
}
_fileInfo = null;
_fileInfo = temp_fileInfo;
PDF_FILE_PATH = FilePath + _fileInfo.FileNm;
DirectoryInfo di = new DirectoryInfo(FilePath);
if (di.Exists == false)
{
di.Create();
}
if (!File.Exists(PDF_FILE_PATH))
File.WriteAllBytes(PDF_FILE_PATH, _fileInfo.FileData);
if (!PDF_FILES.Contains(PDF_FILE_PATH))
{
PDF_FILES.Add(PDF_FILE_PATH);
}
WebBrowserPdf.Navigate(PDF_FILE_PATH + "?#zoom=" + _zoomFactor + "%", false);
WebBrowserPdf.Visible = true;
simpleButtonOpenPOPUP.Enabled = true;
}
else
{
WebBrowserPdf.Visible = false;
simpleButtonOpenPOPUP.Enabled = false;
}
}
}
catch (Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Alert, true);
}
}
it is Load Method
private void w_pcmu081_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
WebBrowserPdf.Dispose();
Process[] Pro = Process.GetProcessesByName("osk");
if (Pro.GetLength(0) > 0)
Pro[0].Kill();
}
catch(Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Info, true, null, true);
}
}
Closing
The same situation happened to me.
Adobe has done something wrong in the latest version of Acrobat Reader DC (15.023.20056).
If you uncheck option Enable Protected Mode at startup in Edit -> Preferences -> Security (Enhanced), everything will be back to normal.
On my case it is not a solution.
More info here: https://forums.adobe.com/thread/2267688

Previous Page state lost on back key press

I am creating a Windows Phone 8.1 Universal App. There are some screens on my app. On the first screen, i am navigate my screen to second screen. When i press hardware back button on second screen. My previous page state lost.
I am unable to rectify where was the problem. Here is the code below:
Screen 1 Code
protected override void OnNavigatedTo(NavigationEventArgs e)
{
this.navigationHelper.OnNavigatedTo(e);
this.NavigationCacheMode = NavigationCacheMode.Enabled;
if (e.NavigationMode == NavigationMode.New)
{
BindQuickDateComboBox();
if (Frame.BackStack.Count > 0)
{
var lastPage = Frame.BackStack.Last().SourcePageType;
if (lastPage != null && lastPage.FullName == "Cryoserver.AppLogin")
{
Frame.BackStack.Clear();
}
}
}
}
async private void appBarSearch_Click(object sender, RoutedEventArgs e)
{
try
{
if (IsValidateForm())
{
ProgressBar.IsVisible = true;
cmdBarSearch.IsEnabled = false;
if (await conn.Table<SearchQuery>().CountAsync() > 0)
{
await conn.DropTableAsync<SearchQuery>();
await conn.CreateTableAsync<SearchQuery>();
}
var searchTerms = new SearchQuery();
if (Convert.ToString(cmbQuickDate.SelectedItem) != "Any Date")
{
searchTerms.FromDate = pickerFromDate.Date.ToString("d MMM yyyy");
searchTerms.FromTime = pickerFromTime.Time.ToString();
searchTerms.ToDate = pickerToDate.Date.ToString("d MMM yyyy");
searchTerms.ToTime = pickerToTime.Time.ToString();
}
searchTerms.SearchKeywords = txtKeywords.Text;
searchTerms.Parties = txtParties.Text;
searchTerms.Contributer = txtFrom.Text;
searchTerms.Viewer = txtTo.Text;
searchTerms.AttachmentName = txtAttName.Text;
searchTerms.AttachmentKeywords = txtAttKeywords.Text;
searchTerms.SearchReason = txtSearchReason.Text;
searchTerms.IsHighLight = "false";
await conn.InsertAsync(searchTerms);
object resultMails = await SearchEmailArchive();
if (!String.IsNullOrEmpty(Convert.ToString(resultMails)))
{
GlobalInfo.SelectedRow = -1;
GlobalInfo.SearchPageIndex = -1;
GlobalInfo.IsFindKeyword = false;
var archiveMails = JsonConvert.DeserializeObject<SearchResult>(resultMails.ToString());
Frame.Navigate(typeof(MailList), archiveMails);
}
ProgressBar.IsVisible = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
ProgressBar.IsVisible = false;
}
cmdBarSearch.IsEnabled = true;
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
}
Screen 2
I too used this code in second screen and also after removing this code. But it didn't work for me. Still the same problem.
void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
Screen 1 state is Blank and behaves as a freshly loaded screen. Why?
Any help would be much appreciated.
I would try setting NavigationCacheMode="Required" in the constructor/XAML instead.

Categories