Giving the editor focus with visual studio addin code - visual-studio-2012

I have the following code which opens a visual studio ProjectItem node programatically as a code editor view.
void Commit(object sender, KeyPressEventArgs args)
{
if (args.KeyChar == (char)Keys.Return)
{
Close();
var selected = _FilteredList.FirstOrDefault();
if (selected != ""){
var item = _Items.Where(x => x.Name == selected).First();
if (item!=null)
{
Window win = item.Open(Constants.vsViewKindCode);
win.Visible = true;
win.SetFocus();
}
}
}
}
The problem is that the editor belonging to the window win is brought
to the top of the tab stack but the cursor doesn't give the editor focus.
Any trick to move the cursor focus to the editor?

This is worked for me:
Project activeProject = _applicationObject.Solution.Projects.Item(1);
ProjectItem a = activeProject.ProjectItems.Cast<ProjectItem>().FirstOrDefault(item => item.Name.EndsWith(".cs"));
Window win = a.Open();
win.Activate();
_applicationObject.ExecuteCommand("Edit.GoTo", String.Format("{0}", 2));
_applicationObject.ExecuteCommand("Edit.CharRight");
You can move the cursor to the required line with the "Edit.GoTo" command.
If you need to edit the code maybe an EditPoint is a better choice:
TextSelection ts;
ts = (TextSelection)_applicationObject.ActiveDocument.Selection;
EditPoint ep = (ts.ActivePoint).CreateEditPoint();
ep.StartOfDocument();

Related

WebView2 - Viewing Page Source via Context Menu in popup window

I know that there are several questions around the theme of page source but they don't seem related to my issue. I have also asked this question on the WebView2 GitHub website but it was closed.
Goal
I have an embedded WebView2 control on my CDialog and I am implementing a custom menu. I want to be able to view the page source and it should show in a popup. In-fact, it should show exactly as when you press CTRL + U in the browser control:
Issue
I added the following custom menu event handler to display the page source:
// ===============================================================
wil::com_ptr<ICoreWebView2ContextMenuItem> itemViewPageSource;
CHECK_FAILURE(webviewEnvironment->CreateContextMenuItem(
L"View Page Source (CTRL + U)", nullptr,
COREWEBVIEW2_CONTEXT_MENU_ITEM_KIND_COMMAND, &itemViewPageSource));
CHECK_FAILURE(itemViewPageSource->add_CustomItemSelected(
Callback<ICoreWebView2CustomItemSelectedEventHandler>(
[appWindow = this, target](ICoreWebView2ContextMenuItem* sender, IUnknown* args)
{
wil::unique_cotaskmem_string pageUri;
CHECK_FAILURE(target->get_PageUri(&pageUri));
CString strUrl = L"view-source:" + CString(pageUri.get());
appWindow->NavigateTo(strUrl);
//appWindow->m_pImpl->m_webView->ExecuteScript(L"window.open(\"" + CString(pageUri.get()) + L"\", \"\", \"width=300, height=300\")", nullptr);
return S_OK;
})
.Get(), nullptr));
CHECK_FAILURE(items->InsertValueAtIndex(itemsCount, itemViewPageSource.get()));
itemsCount++;
// ===============================================================
The problem is that the source is not displayed in a new popup window (like when using the hotkey):
Update 1
I was able to change the code to use some JavaScript to display the page itself in a new window:
appWindow->m_pImpl->m_webView->ExecuteScript(L"window.open(\"" + CString(pageUri.get()) + L"\", \"\", \"width=300, height=300\")", nullptr);
And then, when I tried CTRL + U on the popup window, it appeared to display the source in the same window. But in actual fact it was a new window, as I could move it:
At this time I have not found out how to display the page source in a popup-up window (given teh context of my browser control) just like when you press CTRL + U.
The easiest way to do this is why the SendInput API:
CHECK_FAILURE(itemViewPageSource->add_CustomItemSelected(
Callback<ICoreWebView2CustomItemSelectedEventHandler>(
[appWindow = this, target](ICoreWebView2ContextMenuItem* sender, IUnknown* args)
{
wil::unique_cotaskmem_string pageUri;
CHECK_FAILURE(target->get_PageUri(&pageUri));
CString strUrl = L"view-source:" + CString(pageUri.get());
// Create an array of generic keyboard INPUT structures
INPUT ip[4] = {};
for (int n = 0; n < 4; ++n)
{
ip[n].type = INPUT_KEYBOARD;
ip[n].ki.wScan = 0;
ip[n].ki.time = 0;
ip[n].ki.dwFlags = 0; // 0 for key press
ip[n].ki.dwExtraInfo = 0;
}
ip[0].ki.wVk = VK_CONTROL;
ip[1].ki.wVk = 'U';
ip[2].ki.wVk = 'U';
ip[2].ki.dwFlags = KEYEVENTF_KEYUP;
ip[3].ki.wVk = VK_CONTROL;
ip[3].ki.dwFlags = KEYEVENTF_KEYUP;
SendInput(4, ip, sizeof(INPUT));
return S_OK;
})
.Get(), nullptr));
CHECK_FAILURE(items->InsertValueAtIndex(itemsCount, itemViewPageSource.get()));
itemsCount++;

How to debug a new Thread in VS2015?

I have this code in a WebForm project in VS Community 2015:
var th = new Thread(() => {
var wb = new WebBrowser();
wb.DocumentCompleted += wb_DocumentCompleted;
wb.AllowNavigation = true;
wb.Navigate("https://www.ovo.com.au/login");
Application.Run();
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
This is the DocumentCompleted handler, which runs ok, but I cannot debug it
private async void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
WebBrowser wb = (WebBrowser)sender;
System.Diagnostics.Debug.WriteLine(wb.Url);
}
I get this in the Watch window when I put a breakpoint:
error CS0103: The name 'wb' does not exist in the current context
Edit / Solution
The solution was to enable "Use Managed Compatibility Mode" (in Tools > Options > Debugging > General)

ZXing.Net.Mobile Sample.WindowsUniversal Sample Not Scanning

Testing this to incorporate into Win 10 UWP app to scan 1D barcodes (format 39 & 128). I have updated latest through nuget 2.0.4.46. Referenced post at http://www.yortondotnet.com/2015/07/mobile-barcode-scanning-with-zxingnet.html regarding some options setting prior to scan() with no luck. The scanner (camera) opens but never recognizes a barcode scan successfully - or failure for that matter. It seems nothing is happening whatsoever. I have included straight, pertinent sample code with some options modifications for review. I have gotten Scandit API to work and was going to try Manateeworks but both are really costly and not an option. I am developing on Surface Pro 3 (Win 10) and that build will also be target machines when complete.
public sealed partial class MainPage : Page
{
UIElement customOverlayElement = null;
MobileBarcodeScanner scanner;
public MainPage()
{
this.InitializeComponent();
//Create a new instance of our scanner
scanner = new MobileBarcodeScanner(this.Dispatcher);
scanner.Dispatcher = this.Dispatcher;
}
private void buttonScanDefault_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.Scan(options).ContinueWith(t =>
{
if (t.Result != null)
HandleScanResult(t.Result);
});
}
private void buttonScanContinuously_Click(object sender, RoutedEventArgs e)
{
//Tell our scanner to use the default overlay
scanner.UseCustomOverlay = false;
//We can customize the top and bottom text of our default overlay
scanner.TopText = "Hold camera up to barcode";
scanner.BottomText = "Camera will automatically scan barcode\r\n\r\nPress the 'Back' button to Cancel";
// GWS Set Options
var options = new MobileBarcodeScanningOptions();
options.PossibleFormats = new List<ZXing.BarcodeFormat>() {
ZXing.BarcodeFormat.CODE_39, ZXing.BarcodeFormat.CODE_128
};
options.AutoRotate = false;
options.TryHarder = false;
options.TryInverted = false;
//Start scanning
scanner.ScanContinuously(options, async (result) =>
{
var msg = "Found Barcode: " + result.Text;
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
await MessageBox(msg);
});
});
}
async void HandleScanResult(ZXing.Result result)
{
string msg = "";
if (result != null && !string.IsNullOrEmpty(result.Text))
msg = "Found Barcode: " + result.Text;
else
msg = "Scanning Canceled!";
await MessageBox(msg);
}
}
Simon,
I have the exact same problem. I tested your code with the latest nuget 2.1.47, the problem still exists.
You need to download the latest from Github and add the following projects (or DLLs) to your project:
ZXing.Net (project: zxing.portable.csproj)
ZXing.Net.Mobile.Core
ZXing.Net.Mobile.WindowsUniversal
I have tested your code and it works fine. I hope this help.
Cheers,
Sam
I think that the problem in the hardware you are testing with. Surface Pro 3 (Win 10) does not have an auto focus camera. I've never succeed to scan with ZXing using my Surface Pro 3, while the same application is working fine with my other windows 10 device.

how to close print dialog when user cancel print preview dialog

I need some help.
My requirement is when the user click on print button it should show a print preview dialog.
if user cancel or close the preview dialog the form must be return to original.
the problem i am facing is print preview dialog box is visible. but i don't know how to capture the print preview tools click events.
public void print()
{
PrintDialog pd = new PrintDialog();
PrintDocument pdoc = new PrintDocument();
PrinterSettings ps = new PrinterSettings();
PaperSize psize = new PaperSize();
pdoc.DefaultPageSettings.Landscape = false;
pd.Document = pdoc;
pd.Document.DefaultPageSettings.PaperSize = psize;
pdoc.PrintPage += new PrintPageEventHandler(pdoc_PrintPage);
DialogResult result = pd.ShowDialog();
if (result == DialogResult.OK)
{
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = pdoc;
ppd.ShowDialog();
pdoc.Print();
}
}
if i place the PrintPreviewDialog code before pd.ShowDialog() nothing visible in the preview mode.
this not working
PrintPreviewDialog ppd = new PrintPreviewDialog();
ppd.Document = pdoc;
ppd.ShowDialog();
DialogResult result = pd.ShowDialog();
if (result == DialogResult.OK)
{
pdoc.Print();
}
DialogResult is not supported in showdialog() with print dialog .
so the worked way is true or false
PrintDialog pri = new PrintDialog();
if (pri.ShowDialog() == true)
{
pri.PrintQueue.AddJob(fileName, fileName,false);
}
else
{
return;
}
you can also not to use pri.ShowDialog() as the if statement already invoking the method also .

How to get drives( 'C' or 'E' or 'F' )available in a system?

I am developing an Bootstrapper application. When we move to the installation location selection wizard, we can have a browse option to change the location of our setup installation.
When we clock that browse option, i need to show only the drives( 'C', 'D' and 'F') available in a system. When we select the drive, it will not expand. i need that drive alone (Ex: C:) in the installation location text in the installation wizard.
Can anyone please guide me that how to achieve my requirement?
My code:
private void btn_Browse_Click(object sender, EventArgs e)
{
txt_InstallLocation.Focus();
FBD_Source.RootFolder = Environment.SpecialFolder.Desktop;
if (FBD_Source.ShowDialog() == DialogResult.OK)
{
txt_InstallLocation.TextBox.Text = FBD_Source.SelectedPath;
BA.Model.Bootstrapper.Engine.StringVariables["APPDIR"] = FBD_Source.SelectedPath + "\\";
}
}
I need to modify the below line of code.
FBD_Source.RootFolder = Environment.SpecialFolder.Desktop;
Can anyone please assist me to proceed further or direct me in right path?
Your can find the available drives like this.
var drives = System.Environment.GetLogicalDrives();
foreach (string d in drives)
Console.WriteLine(d);
Don't use the FolderBrowserDialog.
Create a form with a dynamically created radiobutton/list and make the user select one of those options
Something like this
var drives = System.Environment.GetLogicalDrives();
Form selectionForm = new Form() { MaximizeBox = false, FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog, StartPosition = FormStartPosition.CenterScreen };
ListBox lb = new ListBox() { Dock = DockStyle.Fill };
foreach (var item in drives)
lb.Items.Add(item);
selectionForm.Controls.Add(lb);
Button btnOk = new Button() { Dock = DockStyle.Left, Width = selectionForm.Width / 2 };
btnOk.Text = "OK";
Button btnCancel = new Button() { Dock = DockStyle.Right, Width = selectionForm.Width / 2 };
btnCancel.Text = "Cancel";
Panel bottomPanel = new Panel() { Dock = DockStyle.Bottom, Height = 50 };
bottomPanel.Controls.Add(btnOk);
bottomPanel.Controls.Add(btnCancel);
selectionForm.Controls.Add(bottomPanel);
selectionForm.ShowDialog();
MessageBox.Show(lb.SelectedItem.ToString());

Resources