Weird behavior caused by using .Net ComboBox properties SelectionStart & SelectionLength in “DropDownList” mode

自作多情 提交于 2019-12-24 21:25:04

问题


We have a sample application with such handler for a combobox in "DropDownList" mode:

    private void comboBox1_Leave(object sender, EventArgs e)
    {
        comboBox1.SelectionStart = 0;
        comboBox1.SelectionLength = 0;
    }

the code above behaves differently depending whether the application has CALLWNDPROC hook loaded or not. If application has a CALLWNDPROC hook in it - the code above would throw exception whenever combobox loses focus. Without the hook - that code doesn't throw.

these are few lines from exception description:

System.ArgumentOutOfRangeException: InvalidArgument=Value of '-2136611475' is not valid for 'start'.
Parameter name: start
   at System.Windows.Forms.ComboBox.Select(Int32 start, Int32 length)
   at System.Windows.Forms.ComboBox.set_SelectionLength(Int32 value)
   at ComboCrash.Form1.comboBox1_Leave(Object sender, EventArgs e) in T:\tmp.proj\ComboCrash\ComboCrash\Form1.cs:line 32
   at System.Windows.Forms.Control.OnLeave(EventArgs e)
   at System.Windows.Forms.Control.NotifyLeave()
   at System.Windows.Forms.ContainerControl.UpdateFocusedControl()

The question is: What might be the cause of that different behavior with a hook installed?

PS1: I am not a C# developer, but it seems to me that concept of textual selection is not applicable for DropDownList comboboxes (as they don't have a textbox), is it correct?

PS2: Application that installs the hook and a hook DLL are written in C++. Hook function is as simple as:

return (CallNextHookEx(hook_handle, code, wParam, lParam));

回答1:


ok, as there are no suggestions yet I'll provide some:

  1. it is not correct to work with SelectionStart and SelectionLength properties if your combobox is a DropDownList. In these cases CB_GETEDITSEL is sent to combobox's window - and it will not return anything reliable (because there is no edit control to query). So - just don't do that (or enclose corresponding code with try-catch)! Or - always check the type of your combobox.
  2. violation of the previous recommendation might result in (a) nothing unusual; (b) an unhandled exceptions or abnormal program termination (depending on JIT settings). Case (b) is very stable in case if there are system-wide WH_CALLWNDPROC hooks installed in your environment.

Update on February 2011 As I mentioned somewhere in the comments here, only workaround (read - dirty hack) was to install your own hook of the same type (WH_CALLWNDPROC), but don't invoke other hooks if the message is for your combobox. Yes, it's ugly.



来源:https://stackoverflow.com/questions/944263/weird-behavior-caused-by-using-net-combobox-properties-selectionstart-selecti

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!